While converting double 0.10 double.parse() converts to 10.0 - c#

I have a simple console application in visual studio for testing some code before going big.
But now i have a problem with parsing some string to double.
When the users input is a String: 0.10 i want to convert this to a double.
So the output should be a double: 0.10.
But when i do this with the following code:
double r_value = 0;
r_value = Math.Round(double.Parse(value), 2);
Or
r_value = double.Parse(value);
The output will be: 10 or 10.0.
How can it be this output changes like this? and converts to 10.0 instead 0.10 as i thought it should be.

I strongly suspect your default culture is one in which . is a grouping separator (usually for thousands). So where an English person might write ten thousand as "10,000" some other cultures would write "10.000". At that point, your output makes sense.
If you want to parse with the invariant culture (which treats . as a decimal separator and , as the grouping separator) do so explicitly:
double r_value = double.Parse(value, CultureInfo.InvariantCulture);

Related

How to convert an integer value to a special format

I have a numeric value. I want to format it like this:
input: 500000 $
output: 500.000 $
How do I do that?
You can use custom format strings to handle displaying the number the way you want without having to actually change its value.
As long as that dot character is actually a thousands separator in your culture, you can use the format string ##,# $.
var value = 50000;
Console.WriteLine(value.ToString("##,# $"));
# acts as a numeric place holder,
, acts as the separator (this
particular string can handle larger numbers, the groups are repeated for each "thousand" grouping, see this for more detail on how it works),
$ is displayed
literally.
The output is : 50.000 $ as requested.
Also, because this formatting is culture dependant, it will display correctly if the program happens to be run in a country that uses a different separator.
If 500.000 $ happens to be the "normal" way your culture displays currency, you can use the standard format string C0. This simple formats the number with your culture's default currency format, with 0 decimal places. This will also automatically adjust for the culture of the person running the application.
If you do NOT want these to adjust to the culture format of the user, you can pass an explicit culture to ToString.
var value = 50000;
var culture = new CultureInfo("fr-FR");
Console.WriteLine(value.ToString("C0", culture));
This will display 500 000 € on my machine, even though the default culture (en-US) would cause it to display $50,000
Your question is quite easy to solve and you should be able to do it.
In pseudocode (You are gonna have to write the program):
float num
Writeline input number;
read line num;
num = num / 1000;
print num;

Convert.ToSingle(string) C# conversion ambiguity

I have this code:
string x = "-0.228469369833477";
Single s = Convert.ToSingle(x);
Console.WriteLine(s);
The console outputs: -2,284694E+14 .
What can I do to make it output: -0.228469369833477?
To output the number in its original form:
var s = -0.228469369833477;
Console.WriteLine(s.ToString("0.#######################"));
Note that s is likely a double, not a single. By using single you're very likely losing digits. To get enough precision to represent all of the digits, use Convert.ToDouble() instead.
To ensure that the number gets parsed properly in your locale, use CultureInfo.InvariantCulture, as other answers have stated.
A decimal will give you 28-29 significant digits of precision, with better precision and without the scientific notation problems.
Further Reading
Custom Numeric Format Strings
Single s = Single.Parse(x, CultureInfo.InvariantCulture);
If you want it to output that exact number, you can't use a float because it doesn't give you the precision you want. Try using a double.
double s = Double.Parse(x, CultureInfo.InvariantCulture);
Well, '.' is treated as a thousand separator (and ',' as decimal one) in your current culture (e.g. Russian Culture - "RU-ru" works like that) and since thousand separator ignored on conversion you have -228469369833477 (or -2,284694E+14).
string x = "-0.228469369833477";
// To ensure that '.' is treated as decimal separator
// lets put culture explicitly - CultureInfo.InvariantCulture
Single s = Convert.ToSingle(x, CultureInfo.InvariantCulture);
Console.WriteLine(s);
However, you have too many digits to represent for a Single and all you can return is -0.2284694 (not -0.228469369833477). If you want exact correspondence you have to use Double instead of Single:
Double s = Convert.ToDouble(x, CultureInfo.InvariantCulture);
// -0.228469369833477
Console.WriteLine(s, CultureInfo.InvariantCulture);
You can use
Console.WriteLine(string.Format("{0:N8}", s));
to output the single to 8 decimal places.
You can also specify the culture while doing the string formatting:
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:N8}", s));
Here's a working fiddle: https://dotnetfiddle.net/nS9qXh

Converting double to string 1

I'm new to C#, I'm currently making a calculator, I want to make a simple calculation but it doesn't work properly.
Here is the current line:
Convert.ToString(Convert.ToDouble(A.Text)+Convert.ToDouble(B.Text)+Convert.ToDouble(C.Text));
Here is a sample output with 1.1 in every textbox:
1.1+1.1+1.1 = 33
The problem is that you are not specifying the culture in your conversions. Most likely you have a German culture (or some other European one) which uses the dot as group separator, not as the decimal point. The result is that 1.1 is interpreted as 11.
There are two solutions:
Enter your numbers in the current culture: 1,1 (Preferred)
Parse the numbers using the invariant culture:
Convert.ToString(
Convert.ToDouble(A.Text, CultureInfo.InvariantCulture) +
Convert.ToDouble(B.Text, CultureInfo.InvariantCulture) +
Convert.ToDouble(C.Text, CultureInfo.InvariantCulture),
CultureInfo.InvariantCulture)
The first approach is preferred, because it will ensure that the user can always enter the numbers in its own culture. Forcing a certain culture on users is something that was acceptable 20 years ago, but not nowadays.
You need to caluculate the sum and then add the parts together.
String.Format is a nice way to concat strings.
double sum = Convert.ToDouble(A.Text)+Convert.ToDouble(B.Text)+Convert.ToDouble(C.Text);
string resultStr = String.Format("{0}+{1}+{2}={3}", A.Text, B.Text, C.Text, sum);
You should assign your intermediate results to a double-variable first and then put it to a string, i.e.
double d = Double.Parse(A.Text) + Double.Parse(B.Text) + Double.Parse(C.Text);
Eventually you can just call
string result = d.ToString();
This is far easier.
See here.

Formatting a String to be Converted to Double

I'm trying to convert a string to double. The incoming string is always going to be a whole number...no decimals. So, for example "90".
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
SomePercentTrigger is the % that I will be converting.
I get a "string is not in the correct format" error so how should I format this string? I've got to format it because if I don't I get the same error with just this during the conversion:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
UPDATED:
SomePercentTrigger is simply a string such as "80"..it'll always be a whole number too.
Update:
Your string is "52.0".
It must be the '.' that causes the FormatException.
You are probably on a machine where '.' is not set as the decimal point (e.g. I live in Germany and use German regional settings. Our decimal point is ',' )
To get around this problem you need to parse the string using CultureInfo.InvariantCulture.
var value = double.Parse(myString, CultureInfo.InvariantCulture);
InvariantCulture should be used for the parts of your application that revolve around data storage. Make sure you use it as well when converting doubles to strings Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
I suspect that SomeEntity.KeyIDs.SomePercentTrigger has some invalid characters in it (something other than digits, '.' and a optional leading '-'), say for example "80%"
So you're getting a FormatException on this line
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
because {0:0.00} formatting rules are only valid for numeric values.
Also you get the very same exception here:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
because "80%" can not be converted into a double.
You should either
put some logging right in front of the failing statement
or debug that code
and see what the actual content of SomeEntity.KeyIDs.SomePercentTrigger is.
Use double.Parse(string) or alternatively double.TryParse(string, out value)
It doesn't make sense to try to format a string. You would have to parse it to a number first in order to format it. Anyhow, there is no problem in parsing a number without decimals as a double, so the string is probably not containing what you think it does.
If the string contains a number in integer format, parse the string as an integer, and then convert the integer to a double:
double percentToCheck = (double)Int32.Parse(SomeEntity.KeyIDs.SomePercentTrigger);

Defining decimal numbers on different operation system, how to understand if point or comma is used by C#

I have written a small program where the program works differently on different operating systems (xp, win7) The problem is the program reads some float numbers such 2,686.
One operating system (win7) convert it to float true, but on xp it goes wrong and print it 2686. How can I understand which symbol the operation system uses for decimal numbers ?
Thanks.
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
This does not depend on the operating system but at the (default) language settings on each PC.
If you use : double value = double.Parse(text); you are using whatever culture the user has configured. If you know the input to be in a certain format, use:
var ci = CultureInfo.GetCulture("nl-NL"); // dutch
double value = double.Parse(text, ci);
Every function that converts has (1 or more) overloads to take a FormattingProvider (Culture).
parse the floating point numbers using the user current culture with double.Parse(string, System.Globalization.CultureInfo.CurrentCulture);
The decimal separator is decided by the current culture.
If you want to use a specific character as decimal separator, you can create a custom NumberFormatInfo object with any separator you like. If you want to use period as deimcal separator, you can simply use InvariantCulture:
double n = Double.Parse(s, CultureInfo.InvariantCulture);
If you want to use comma, you can choose a culture that has that, for example swedish:
double n = Double.Parse(s, CultureInfo.GetCultureInfo("sv-SE"));

Categories

Resources