Convert string to double with 2-digit after decimal separator

It all started with these simple lines of code:

string s = "16.9"; double d = Convert.ToDouble(s); d*=100; 

The result should be 1690.0, but it is not. d is 1689.999999999999998. All I want to do is round the double value to 2 digits after the decimal separator. Here is my function.

 private double RoundFloat(double Value) { float sign = (Value < 0) ? -0.01f : 0.01f; if (Math.Abs(Value) < 0.00001) Value = 0; string SVal = Value.ToString(); string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator; int i = SVal.IndexOf(DecimalSeparator); if (i > 0) { int SRnd; try { //       SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1)); } catch { SRnd = 0; } if (SVal.Length > i + 3) SVal = SVal.Substring(0, i + 3); //SVal += "00001"; try { double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal); //result = Math.Round(result, 2); return result; } catch { return 0; } } else { return Value; } 

But again, the problem is, converting from string to double does not work as I want. The workaround for this problem is to associate β€œ00001” with the string, and then use the Math.Round function (commented on in the example above).

This double value, multiplied by 100 (as an integer), is sent to the device (cash register), and these values ​​must be correct.

I am using VS2005 + .NET CF 2.0

Is there an even more "elegant" solution, I am not satisfied with this.

+4
source share
3 answers

Parties cannot represent exactly 16.9. I suggest you convert it to decimal instead:

 string s = "16.9"; decimal m = Decimal.Parse(s) * 100; double d = (double)m; 

You can simply use decimal instead of double , as you say that you will use it for monetary purposes. Remember that decimal intended to accurately represent decimal numbers that match its precision, and double will accurately represent only binary numbers.

+12
source
 Math.Round(number, 1) 

Change I asked the wrong question - rounding problems are inherent in the floating point type (float, double). You must use a decimal value for this.

+1
source

The best solution for unsuccessful is: string s = "16.9";

For, /. double d = Convert.ToDouble (s.Replace (',', '.'), System.Globalization.CultureInfo.InvariantCulture);

For rounding: Convert.ToDouble ((d) .ToString ("F2"));

+1
source

All Articles