Click here to Skip to main content
15,921,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have the following issue in c++.

std::string num = "0.6";
float temp = ::strtof(num.c_str(), nullptr);

Output:
0.600000024


std::string num = ""2999.6";
float temp = ::strtof(num.c_str(), nullptr);

Output:
2999.60010


How to avoid this precision issue ?

What I have tried:

I have tried using sscanf_s
float myAtof(string& num) 
{
	floattmp;
	sscanf_s(num.c_str(), "%f", &tmp);
	return tmp;
}

float myround(float var)
{
	float value = (int)(var * 100 + .5);
	return (float)value / 100;

}


But this does not provide the result expected as 0.6 and 2999.6

Could somebody explain me how to get the value properly converted.
Thanks in advance.
Posted
Updated 13-Nov-19 10:22am
Comments
Richard MacCutchan 13-Nov-19 12:39pm    
As OriginalGriff says below, the values have been converted. You need to set the precision for display when you print them.

Short version: because computers don't store values in decimal, they use base 2. And that means that numbers that look simple in base 10 cannot be represented accurately as floating point values.

Longer version: 4.8 — Floating point numbers | Learn C++[^]
 
Share this answer
 
Comments
SuperMiQi 13-Nov-19 12:56pm    
Hello,

Thank you for your reply.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900