简体   繁体   中英

parse float from string

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM