I am trying to multiply two floats as follows:
float number1 = 321.12;
float number2 = 345.34;
float rexsult = number1 * number2;
The result I want to see is 110895.582, but when I run the code it just gives me 110896. Most of the time I’m having this issue. Any calculator gives me the exact result with all decimals. How can I achive that result?
edit : It’s C code. I’m using XCode iOS simulator.
There’s a lot of rounding going on.
I get 110895.578125000000000 after the three separate roundings.
If you want more than 6 decimal digits’ worth of precision, you will have to use
doubleand notfloat. (Note that I said “decimal digits’ worth”, because you don’t get decimal digits, you get binary.) As it stands, 1/2 ULP of error (a worst-case bound for a perfectly rounded result) is about 0.004.If you want exactly rounded decimal numbers, you will have to use a specialized decimal library for such a task. A
doublehas more than enough precision for scientists, but if you work with money everything has to be 100% exact. No floating point numbers for money.Unlike integers, floating point numbers take some real work before you can get accustomed to their pitfalls. See “What Every Computer Scientist Should Know About Floating-Point Arithmetic“, which is the classic introduction to the topic.
Edit: Actually, I’m not sure that the code rounds three times. It might round five times, since the constants for
aandbmight be rounded first to double-precision and then to single-precision when they are stored. But I don’t know the rules of this part of C very well.