1

I have some problem with parsing float value from string.
Problem is with decimal part of value, here is example:

var tmp = "263148,21";
var ftmp = float.Parse(tmp); //263148.219

I tried some other values, but I don't figured out, from what reason are some decimal values incorrect.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
davidm
  • 23
  • 6

3 Answers3

3

This doesn't have anything to do with the comma in the OP's code - instead, this question is about a float value not accurately representing a real number.

Floating point numbers are limited in their precision. For really precise numbers you should use double instead.

See also this answer: why-is-floating-point-arithmetic-in-c-sharp-imprecise? and have a look at this for more information: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Community
  • 1
  • 1
Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35
  • 1
    Any explanation for the down vote? This answer is correct in it's observation of the inherent precision limitations of the `float` type. If you have a problem with my answer, please leave a comment. – Matt Hogan-Jones May 18 '15 at 10:49
  • 4
    I can't believe how people are voting on this question. This answer is the only one that addresses the actual problem. This question has nothing to do with culture-specific formatting. I can't understand why those answers get up-voted. – Nico Schertler May 18 '15 at 10:50
  • @Matt Jones posted some good articles completely explaining why float type numbers like 0.1 are represented as something like 0.099999955. It's how the number is represented in binary that causes this. Some say never use float in calculations but there are many places to use float, but just like in Chemistry or Physics you have to pay attention to your significant figures and margin of error – waltmagic May 22 '15 at 16:44
1
var tmp = "263148,21";
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ",";
var ftmp = double.Parse(tmp, culture);

You have to use double instead of float

Utamaru
  • 848
  • 7
  • 19
0

As stated in other answers and comments, this is related to floating point precision.

Consider using Decimal if you need to have the exact same decimals or to leverage rounding errors. But please note that this type is much more heavy weight (128 bits) and might not be suited for your case.

var tmp = "263148,21";
var dtmp = Decimal.Parse(tmp); //263148.21
Kryptos
  • 875
  • 8
  • 19