I'm new to swift (using swift 2.2) and I'm seeing an issue where 200.23 - 200
is shown to be equal to 0.2299999999999898
. I know that computers can't represent irrational numbers accurately, but I don't understand why a rational number is also not being represented correctly. This is affecting the output numbers generated by my program, leading to issues.
Here's a sample playground code (a very simple version of part of my actual code) showing this behavior:
var number:Double = 200.23 //Number I'm testing
var left: Double = floor(number) // Extracting integer part
var right: Double = number-left // Extracting fraction part
In the above code I'm defining a number and then extracting its whole and fractional parts. The fractional part should be 0.23
, however it's shown as 0.2299999999999898
in swift's playground.
Similarly, if I change the original number from 200.23
to 100.23
, then the fractional part is shown to be 0.230000000000004
How can I solve this issue ?
EDIT:
I've been asked about the context of this problem. I'm designing a statistics app that uses numbers a lot and actually has a small builtin calculator too. So if I user tries to calculate 200.23 - 0.23 and sees anything other than 0.23, he's gonna be surprised!