Converting String To Float in C# - c#

I am converting a string like "41.00027357629127", and I am using;
Convert.ToSingle("41.00027357629127");
or
float.Parse("41.00027357629127");
These methods return 4.10002732E+15.
When I convert to float I want "41.00027357629127". This string should be the same...

Your thread's locale is set to one in which the decimal mark is "," instead of ".".
Try using this:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.

You can use the following:
float asd = (float) Convert.ToDouble("41.00027357629127");

First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).
Note: Use always CultureInfo information when dealing with floating point numbers versus strings.
float.Parse("41.00027357629127",
System.Globalization.CultureInfo.InvariantCulture);
This is just an example; choose an appropriate culture for your case.

Use Convert.ToDouble("41.00027357629127");
Convert.ToDouble documentation

The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.

A 2022 way of converting an string that represents a float value:
(float)Convert.ToDecimal(value, CultureInfo.GetCultureInfo("en-US"));
where you also can choose what kind of float are you expecting to convert, because some CultureInfo instances represents decimal values with a , and others with ..
If you need more decimals to obtain more precision, just not use float
Convert.ToDecimal(value, CultureInfo.GetCultureInfo("en-US"));

You can double.Parse("41.00027357629127");

First you need to using System.Globalization to dealing convertions from string to float/double/decimal without problem.
Then you can call Parse on float(or double/decimal depending at the accuracy you need), and as argument in Parse you need your string (you can store it in a variable if you want) and CultureInfo.InvariantCulture.NumberFormat
So, as previous users already explained:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);

You can use parsing with double instead of float to get more precision value.

Related

How to return a double whole number with 2 zeros after the dot? [duplicate]

decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:0.00}", Debitvalue));
I have to get only two decimal places but by using this code I am getting 1156.547.
Which format do I have to use to display two decimal places?
Your question is asking to display two decimal places. Using the following String.format will help:
String.Format("{0:.##}", Debitvalue)
this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).
Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )
Or if you want the currency symbol displayed use the following:
String.Format("{0:C}", Debitvalue)
Use Math.Round() for rounding to two decimal places
decimal DEBITAMT = Math.Round(1156.547m, 2);
If you want to round the decimal, look at Math.Round()
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
I use
decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));
here is another approach
decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));
For only to display, property of String can be used as following..
double value = 123.456789;
String.Format("{0:0.00}", value);
Using System.Math.Round. This value can be assigned to others or manipulated as required..
double value = 123.456789;
System.Math.Round(value, 2);
Another way :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:
someValue.ToString("0.00", CultureInfo.InvariantCulture)
Another option is to use the Decimal.Round Method
If someone looking for a way to display decimal places even if it ends with ".00", use this:
String.Format("{0:n1}", value)
Reference:
https://learn.microsoft.com/pt-br/dotnet/standard/base-types/standard-numeric-format-strings#the-numeric-n-format-specifier
To display two decimal digits, try the given syntax.
string.Format("{0:0.00}", Debitvalue)
In some tests here, it worked perfectly this way:
Decimal.Round(value, 2);
Hope this helps

Convert from double to string without rounding in C#

We have encountered an issue which is the double value is rounded after using .toString() method, in order to show in TextBox.
What we need is something like this:
Double value: 39621443.8975101998
String Value: 39621443.8975101998
But what we get is:
Double value: 39621443.8975101998
String Value: 39621443.8975102
We Have Googled it and tried many methodes, but none of then have worked
Any help would be highly appreciated
If you want exact value with that many decimals you should use the Decimal data type which has higher precision then double. Use decimal.Parse(str).
As #PetSerAl points out, the two values (as represented as an IEEE 754 double precision floating point number) are the same.
39621443.8975101998 => 0x4182E49A1F2E19D4
39621443.8975102 => 0x4182E49A1F2E19D4
39621443.897510199800000123456789 => 0x4182E49A1F2E19D4
Source: BinaryConvert.net.
RoundTrip won't help you here - this is the limit of double precision.
You will need another data type, like #magnus suggests.

C# String to Float

When I convert a string to a float I get my answer plus a bunch of junk decimals. How do I fix this? Is this floats error I'm seeing?
string myFloat = "1.94";
float f = float.Parse(myFloat);
It needs to be a float for database reasons ...
By junk I mean 1.94 turns into: 1.94000005722046
The problem is that you can't use float / double if you want a precise representation of your parsed number. In case you need that you must use decimal. For money amounts its almost always required to use decimal. So keep that in mind.
Please read about how floating point numbers are represented internally:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
How 1.94 is represented internally by a float can be tested in this calculator:
http://pages.cs.wisc.edu/~rkennedy/exact-float?number=1.94
As you see its 1.940000057220458984375.
Databases support the decimal datatype:
Oracle offers DECIMAL: http://docs.oracle.com/javadb/10.6.2.1/ref/rrefsqlj15260.html
SQL Server offers DECIMAL: http://msdn.microsoft.com/de-de/library/ms187746.aspx
MySQL offers DECIMAL: https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
You can change it to a double to get a more accurate representation but if you need it exactly
You cannot fix this this is how floats are represented in computers. If you use the decimal data type you will get an exact representation.
string myFloat = "1.94";
decimal f = decimal.Parse(myFloat);
And then do the conversion to double when you store it to the database. You could still get some noise in the database. The only way to be sure to get rid of this is to use numeric in the database.

C# Convert.ToDouble() loses decimal points when converting string to double

Let's say we have the following simple code
string number = "93389.429999999993";
double numberAsDouble = Convert.ToDouble(number);
Console.WriteLine(numberAsDouble);
after that conversion numberAsDouble variable has the value 93389.43. What can i do to make this variable keep the full number as is without rounding it? I have found that Convert.ToDecimal does not behave the same way but i need to have the value as double.
-------------------small update---------------------
putting a breakpoint in line 2 of the above code shows that the numberAsDouble variable has the rounded value 93389.43 before displayed in the console.
93389.429999999993 cannot be represented exactly as a 64-bit floating point number. A double can only hold 15 or 16 digits, while you have 17 digits. If you need that level of precision use a decimal instead.
(I know you say you need it as a double, but if you could explain why, there may be alternate solutions)
This is expected behavior.
A double can't represent every number exactly. This has nothing to do with the string conversion.
You can check it yourself:
Console.WriteLine(93389.429999999993);
This will print 93389.43.
The following also shows this:
Console.WriteLine(93389.429999999993 == 93389.43);
This prints True.
Keep in mind that there are two conversions going on here. First you're converting the string to a double, and then you're converting that double back into a string to display it.
You also need to consider that a double doesn't have infinite precision; depending on the string, some data may be lost due to the fact that a double doesn't have the capacity to store it.
When converting to a double it's not going to "round" any more than it has to. It will create the double that is closest to the number provided, given the capabilities of a double. When converting that double to a string it's much more likely that some information isn't kept.
See the following (in particular the first part of Michael Borgwardt's answer):
decimal vs double! - Which one should I use and when?
A double will not always keep the precision depending on the number you are trying to convert
If you need to be precise you will need to use decimal
This is a limit on the precision that a double can store. You can see this yourself by trying to convert 3389.429999999993 instead.
The double type has a finite precision of 64 bits, so a rounding error occurs when the real number is stored in the numberAsDouble variable.
A solution that would work for your example is to use the decimal type instead, which has 128 bit precision. However, the same problem arises with a smaller difference.
For arbitrary large numbers, the System.Numerics.BigInteger object from the .NET Framework 4.0 supports arbitrary precision for integers. However you will need a 3rd party library to use arbitrary large real numbers.
You could truncate the decimal places to the amount of digits you need, not exceeding double precision.
For instance, this will truncate to 5 decimal places, getting 93389.42999. Just replace 100000 for the needed value
string number = "93389.429999999993";
decimal numberAsDecimal = Convert.ToDecimal(number);
var numberAsDouble = ((double)((long)(numberAsDecimal * 100000.0m))) / 100000.0;

Rounding of float values

I have the double value like 12.256852651 and I want to display it as 12.257 as a float number without converting it in to a string type.
How can I do it in C# ?
I'd first convert to Decimal and then use Math.Round on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.
Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero)
You should also look into the choice of MidpointRounding, since by default this uses Banker's round, which is not what you are used to from school.
If you want to display it, it will be a string and that's what you need to use.
If you want to round in order to use it later in calculations, use Math.Round((decimal)myDouble, 3).
If you don't intend to use it in calculation but need to display it, use double.ToString("F3").

Categories

Resources