About Monkey 2 › Forums › Monkey 2 Programming Help › Float to String problem
This topic contains 4 replies, has 3 voices, and was last updated by 
 kheldar13 1 year, 6 months ago.
- 
		AuthorPosts
 - 
		
			
				
September 21, 2017 at 2:25 pm #10672
So i have a Float with a value of 3.141
When I try to display that value it actually ends up being 3.140098 or something similar.
is there a way to convert a Float to a String without losing the true value of the number?September 21, 2017 at 4:45 pm #10675Floats are not exact type. For example you can’t have a true 0.1 in float. When you assign the value to the float it will slightly change (if there’s something at the right of the dot).
You will have to round the number in some way if you want to print it with just 3 symbols at the right of the dot.
Don’t know if there is some build in rounder function. BUT you’ll never be shure you get the exact value back because the computer has not stored 3.141 but the nearest float.
For example floats are prohibited in banking applications.September 21, 2017 at 11:44 pm #10682,
September 22, 2017 at 12:40 am #10683Just compared monkey2 with c++, and they were indeed producing different results – monkey2 was printing 3.14100003 and c++ was printing 3.141000
However, peeking the actual variable memory showed they are storing the same value, and it’s really just the string conversion that differs. In fact, monkey2 converts to string with 9 decimals places, whereas c++ printf uses 6 by default. So the monkey2 result is actually a more accurate representation of the underlying value than the c++ result.
Prining to 9 decimal places in c++ produces the same output (it should, monkey2 uses same c++ libs!), ie: 3.14100003.
The ‘9 decimal places precision’ used in monkey2 was chosen because it’s apparently the number of decimal places you need to use to be able to convert *any* possible float value to a string and back without losing any data (I don’t know the proof of this myself).
There are many values like this that are not exactly representable as floating point, try 0.1 for example. Converting this to a string in monkey2 will produce 0.100000001 (and in c++ if done to 9 decimal places). If you check the underlying bit pattern of 0.1, it’s $3DCCCCCD (in both monkey2 and c++) which would suggest some kind of recurring value (in binary of course, suggesting some numbers that don’t recur in decimal may recur in binary and therefore be unrepresentable).
In the case of 3.141 and 0.1, converting to 6 decimal places and back would still work, but I assume there are other values you can produce through math that would require 9 decimals places to represent correctly so I’m in no rush to ‘fix’ this by converting at less precision.
September 22, 2017 at 7:36 pm #10715Thanks for looking into it Mark.
I found a workaround for what I needed. - 
		AuthorPosts
 
You must be logged in to reply to this topic.