String To Float-Problem

BlitzMax Forums/BlitzMax Programming/String To Float-Problem

maverick69(Posted 2011) [#1]
Hi! I want to convert a string to float datatype and some rounding problems are occuring. Do you have some workarounds for me?

Local s:String = "1.4"
Print (s.ToFloat())
Print (Float(s))

Local f:Float = 1.4
Print (f)


Output:
1.39999998
1.39999998
1.39999998

WTF?

I think it is a BlitzMax problem, because similiar code in C++ works as expected:

#include <iostream>

int main (int argc, const char * argv[])
{
    const char *s = "1.4";
    float a = atof(s);
    std::cout << s << "/" << a;
}

Output: 1.4/1.4

Last edited 2011


Shortwind(Posted 2011) [#2]
There is nothing wrong with blitzmax. This is just a good example of how IEEE floats/doubles stupidly store the values. What your actually seeing is the difference between how the cout function differs from the standard Print command in blitzmax. Internally both numbers are stored the same.

Print 1.0
Print 1.1
Print 1.2
Print 1.3
Print 1.4
Print 1.5

This topic has been discussed many times in the forums. It's annoying, but that's just the way it is.

:)


maverick69(Posted 2011) [#3]
Thanks :)


Czar Flavius(Posted 2011) [#4]
What special thing does cout do compared to print?


Floyd(Posted 2011) [#5]
When BlitzMax converts a float or double to a string, such as for use with Print, it uses a fixed number of digits. This is nine digits for a float and seventeen for a double. That guarantees that when a number is converted to a string and the string is converted back to a number the result is exactly the original value.

By default cout rounds a float to six digits. If you set the precision to nine digits the result for 1.4 will look like the BlitzMax output.

#include <iostream>
using namespace std;

int main () {
	float a = atof( "1.4" );
	cout << endl;
	cout << a << endl;
	cout.precision(9);
	cout << a << endl;
}


For those who don't already know, this code can be run from the BlitzMax IDE.

1. Create a new file.
2. Rename it to precision.cpp so it will be recognized as C++.
3. Paste in the C++ code give above.
4. Build and Run as usual.