#include <cwchar>
float flt_Value = wcstof(L"0.8", nullptr);
Why does this return 0.800000012? Is there a way to get a more precise result from wcstof()?
#include <cwchar>
float flt_Value = wcstof(L"0.8", nullptr);
Why does this return 0.800000012? Is there a way to get a more precise result from wcstof()?
Is there a way to get a more precise result from wcstof()?
Not using wcstof
, which will return the best representation of the string as a single-precision, floating point number (see Is floating point math broken?).
However, you can increase the precision by using the double
type for your variable, and calling the wcstod
function.
The following short program will demonstrate the difference (on most platforms):
#include <stdio.h>
#include <cwchar>
int main()
{
float flt_Value = wcstof(L"0.8", nullptr);
printf("%12.10f\n", flt_Value); // 0.8000000119
double dbl_Value = wcstod(L"0.8", nullptr);
printf("%12.10lf\n", dbl_Value); // 0.8000000000
return 0;
}
Note: On systems that support an extended-precision long double
type (mine doesn't), you can further extend the precision as follows:
long double ldbl_Value = wcstold(L"0.8", nullptr);
printf("%22.20Lf\n", ldbl_Value);
Here is the cppreference page for the three conversion functions used.