public static void Main()
{
WriteLine("Farenheit Here>>");
int F = Int32.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
The input works for whole numbers but I also want it to work for Decimal numbers. Ex. If I were to type in 10 it will give me an answer, but if I were to type in 10.5 it will stop working. I am indeed new to C#.
you need to use the number parser you want, currently you are using int
Int32.Parse(ReadLine());
You can use double, or decimal (I'd suggest using decimal over double)
decimal F = Decimal.Parse(ReadLine());
then change to
decimal FtoC = (5.0M / 9.0M) * (F - 32M);
WriteLine("the celsius is {0} ", FtoC)
(the M is used to define decimal literals)
int does not store decimal number. Use double or decimal
public static void Main()
{
WriteLine("Farenheit Here>>");
double F = double.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
Well, Int32 is specifically for handling integers. If you want to handle Decimal values, they have their own Parse method so I'd be looking at something like:
public static void Main() {
Console.Write("Farenheit Here>> ");
Decimal F = Decimal.Parse(Console.ReadLine());
Decimal FtoC = (5.0M / 9.0M) * (F - 32M);
Console.WriteLine("The celsius is {0} ", FtoC);
}
And note the use of the M suffix. If you want to use Decimal types, you're probably better off committing fully to them, rather than reverting to the double type with all its foibles.
Related
I'm trying to create a map-related calculator and I'm having a problem with the Math.Round method. Basically, I want the program to take the real-life length and the length on a map to calculate the scale of said map. After it calculates the scale it should round it from a double to an int.
So for example the real-life length is 3000000 cm and the on map length equals 8,5 cm now after dividing these we get 352 941,176 that's our scalenoteven in this context. Now after rounding it, the scale should be 1:352 941 but instead the program gives me a scale of 1:352.
double Scalenoteven;
int Scaleeven;
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 1, MidpointRounding.ToEven);
So with the added culture info and RealLengthincm = RealLength * 100; this should be working.
using System.Globalization;
double RealLength;
string RealLengthString;
double MapLength;
string MapLengthString;
double RealLengthincm;
double Scalenoteven;
int Scaleeven;
Console.WriteLine("Firstly will the real length be in meters or kilometers?");
string Answer;
Answer = Console.ReadLine();
if (Answer == "meters")
{
Console.WriteLine("Alright!");
Console.WriteLine("So what's the real length?");
var culture = new CultureInfo("de-DE");
RealLengthString = Console.ReadLine(); // assuming 30000
RealLength = double.Parse(RealLengthString, culture);
RealLengthincm = RealLength * 100;
Console.WriteLine("now what's the length on the map in cm");
MapLengthString = Console.ReadLine(); // assuming 8,5
MapLength = double.Parse(MapLengthString, culture);
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 0, MidpointRounding.ToZero);
Console.WriteLine("The Scale is 1:" + Scaleeven); // outputs 1:352941
}
I'm learning C# and im trying to get a custom number to convert to binary. I've looked up several forms here on stack overflow and they have similar code to this, but it doesn't work. Any ideas?
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
double num1 = double.Parse(num1input);
var binary = Convert.ToString(num1, 2);
Console.WriteLine("{0} converted to binary is {1} " ,num1, binary);
It's not clear from your question if you are trying to convert an integer or a floating point value to a binary string representation.
For an integer, use this code:
void Main()
{
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
int num1 = int.Parse(num1input);
var binary = Convert.ToString(num1, 2);
Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}
For a double, this code might be what you want:
void Main()
{
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
double num1 = double.Parse(num1input);
long bits = BitConverter.DoubleToInt64Bits(num1);
var binary = Convert.ToString(bits, 2);
Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}
I found this exercise interesting, so here is what I did :
public IEnumerable<char> ConvertToBase2(int myNumber) {
while(myNumber != 0) {
var returnValue = (myNumber%2 == 0) ? '0' : '1';
myNumber = (myNumber % 2 == 0) ? myNumber / 2 :
(myNumber - 1) / 2;
yield return returnValue;
}
}
Console.Write(String.Concat(
ConvertToBase2(9).Reverse()
));
It works only for integers. I don't remember exactly how floating points numbers are implemented.
By the way, this is a better answer ;-)
I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}
How can I display the number with just the 2 not=zero decimals?
Example:
For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053
There is no built in formatting for that.
You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. Example:
double number = 1.0000533535;
double i = Math.Floor(number);
double f = number % 1.0;
int cnt = -2;
while (f < 10) {
f *= 10;
cnt++;
}
Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);
Output:
1.000053
Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.
My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.
It's not an elegant solution, but I think it will give you consistent results.
Try this function, using parsing to find the # of fractional digits rather than looking for zeros (it works for negative #s as well):
private static string GetTwoFractionalDigitString(double input)
{
// Parse exponential-notation string to find exponent (e.g. 1.2E-004)
double absValue = Math.Abs(input);
double fraction = (absValue - Math.Floor(absValue));
string s1 = fraction.ToString("E1");
// parse exponent peice (starting at 6th character)
int exponent = int.Parse(s1.Substring(5)) + 1;
string s = input.ToString("F" + exponent.ToString());
return s;
}
You can use this trick:
int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
d++;
format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));
In my C# program I have a double obtained from some computation and its value is something like 0,13999 or 0,0079996 but this value has to be presented to a human so it's better displayed as 0,14 or 0,008 respectively.
So I need to round the value, but have no idea to which precision - I just need to "throw away those noise digits".
How could I do that in my code?
To clarify - I need to round the double values to a precision that is unknown at compile time - this needs to be determined at runtime. What would be a good heuristic to achieve this?
You seem to want to output a value which is not very different to the input value, so try increasing numbers of digits until a given error is achieved:
static double Round(double input, double errorDesired)
{
if (input == 0.0)
return 0.0;
for (int decimals = 0; decimals < 17; ++decimals)
{
var output = Math.Round(input, decimals);
var errorAchieved = Math.Abs((output - input) / input);
if (errorAchieved <= errorDesired)
return output;
}
return input;
}
}
static void Main(string[] args)
{
foreach (var input in new[] { 0.13999, 0.0079996, 0.12345 })
{
Console.WriteLine("{0} -> {1} (.1%)", input, Round(input, 0.001));
Console.WriteLine("{0} -> {1} (1%)", input, Round(input, 0.01));
Console.WriteLine("{0} -> {1} (10%)", input, Round(input, 0.1));
}
}
private double PrettyRound(double inp)
{
string d = inp.ToString();
d = d.Remove(0,d.IndexOf(',') + 1);
int decRound = 1;
bool onStartZeroes = true;
for (int c = 1; c < d.Length; c++ )
{
if (!onStartZeroes && d[c] == d[c - 1])
break;
else
decRound++;
if (d[c] != '0')
onStartZeroes = false;
}
inp = Math.Round(inp, decRound);
return inp;
}
Test:
double d1 = 0.13999; //no zeroes
double d2 = 0.0079996; //zeroes
double d3 = 0.00700956; //zeroes within decimal
Response.Write(d1 + "<br/>" + d2 + "<br/>" + d3 + "<br/><br/>");
d1 = PrettyRound(d1);
d2 = PrettyRound(d2);
d3 = PrettyRound(d3);
Response.Write(d1 + "<br/>" + d2 + "<br/>" + d3 +"<br/><br/>");
Prints:
0,13999
0,0079996
0,00700956
0,14
0,008
0,007
Rounds your numbers as you wrote in your example..
I can think of a solution though it isn't very efficient...
My assumption is that you can tell when a number is in the "best" human readable format when extra digits make no difference to how it is rounded.
eg in the example of 0,13999 rounding it to various numbers of decimal places gives:
0
0.1
0.14
0.14
0.14
0.13999
I'd suggest that you could loop through and detect that stable patch and cut off there.
This method seems to do this:
public double CustomRound(double d)
{
double currentRound = 0;
int stability = 0;
int roundLevel = 0;
while (stability < 3)
{
roundLevel++;
double current = Math.Round(d, roundLevel);
if (current == currentRound)
{
stability++;
}
else
{
stability = 1;
currentRound=current;
}
}
return Math.Round(d, roundLevel);
}
This code might be cleanable but it does the job and is a sufficient proof of concept. :)
I should emphasise that that initial assumption (that no change when rounding) is the criteria we are looking at which means that something like 0.3333333333 will not get rounded at all. With the examples given I'm unable to say if this is correct or not but I assume if this is a double issues that the problem is with the very slight variations from the "right" value and the value as a double.
Heres what I tried:
public decimal myRounding(decimal number)
{
double log10 = Math.Log10((double) number);
int precision = (int)(log10 >= 0 ? 0 : Math.Abs(log10)) + (number < 0.01m ? 1 : 2);
return Math.Round(number, precision);
}
test:
Console.WriteLine(myRounding(0.0000019999m)); //0.000002
Console.WriteLine(myRounding(0.0003019999m)); //0.0003
Console.WriteLine(myRounding(2.56777777m)); //2.57
Console.WriteLine(myRounding(0.13999m)); //0.14
Console.WriteLine(myRounding(0.0079996m)); //0.008
You can do it without converting to string. This is what I created fast:
private static double RoundDecimal(double number)
{
double temp2 = number;
int temp, counter = 0;
do
{
temp2 = 10 * temp2;
temp = (int)temp2;
counter++;
} while (temp < 1);
return Math.Round(number, counter < 2 ? 2 : counter);
}
or
private static double RoundDecimal(double number)
{
int counter = 0;
if (number > 0) {
counter = Math.Abs((int) Math.Log10(number)) + 1;
return Math.Round(arv, counter < 2 ? 2 : counter);
}
After giving it another thought I did the following and looks like it does what I want so far.
I iterate over the number of digits and compare Round( value, number ) and Round( value, number + 1 ). Once they are equal (not == of course - I compare the difference against a small number) then number is the number of digits I'm looking for.
Double.ToString() can take a string format as an argument. This will display as many characters as you require, rounding to the decimal place. E.G:
double Value = 1054.32179;
MessageBox.Show(Value.ToString("0.000"));
Will display "1054.322".
Source
Generic formats (i.e, pre-generated)
How to generate custom formats
You can use no of digits with Math.Round Function
Double doubleValue = 4.052102;
Math.Round(doubleValue, 2);
This will return 4.05 as your required answer.
This is tested code, can u explain me how i am wrong. So i need to change.