Handle inaccurracy of float

159 views Asked by At

I have a string

strValue = "11.900000"

I want to parse it to a float value. So I tried:

float fValue = -1;
sscanf_s(strValue.c_str(), "%f", &fValue);

try
{
    double test = std::stod(strValue, &sz);
    fValue = (float) std::stod(strValue, &sz);
}
catch (...)
{
    fValue = -1;
}

For double it is accurate:

test = 11.900000000000000

For float it is inaccurate:

fValue = 11.8999996

Is there a possibility to do this accurately? (I know there is a inaccuracy while working with floats, but is there a better way to do it?)

2

There are 2 answers

1
dlask On

The value 11.8999996 is the most precise approximation of 11.9 that can be represented by the float type.

0
phuclv On

It's not correct for double or any other binary floating-point types. Just print more digits after the radix point and you'll begin to see "garbage" digits soon

The only way for you is to use a decimal floating-point type. If your platform has FLT_RADIX == 10 then you can directly use the built-in float, but obviously it's not your case, and I don't know any current system that uses decimal float except IBM z-series.

So you need a custom type for that. You can use some IEEE-754 decimal32 libraries like IntelĀ® Decimal Floating-Point Math Library or libdfp. Or if you use gcc then it already has support for decimal float via the _Decimal32 type

You can find more information in this question How do I use decimal (float) in C++?