PDA

View Full Version : Qt and decimal number



Imhotep
18th September 2016, 21:16
Hello. I have this fraction:


225/222

the result is this:


1,0135135135135135135135135135135

From this decimal number, it's interesting to me to extract this part


1,013

Then be able to process at a later time. You can do that? If so, how?

Thank you in advance

ChrisW67
18th September 2016, 22:00
#include <cmath>
double result = 225.0/222.0;
double truncatedResult = std::floor(result * 1000) / 1000.0;

Be aware that both results are approximate and continuing to calculate with the truncated result may accumulate errors.
If the result can be negative check how this logic works in your application.

d_stranz
19th September 2016, 16:41
From this decimal number, it's interesting to me to extract this part

Are you sure you aren't confusing how you display the number in your GUI with how you are using the number in your calculations? It's fine to take an irrational number and truncate it for display, but as ChrisW67 says, it probably is not OK to truncate it and then use it for calculations. Every time you use the truncated version, the error in your calculation increases.



225 / 222 = 1.0135135135...
(225 / 222) ^2 = 1.02720964...
(225 / 222) ^3 = 1.0409085...

1.013 ^2 = 1.026
1.013 ^3 = 1.039


Of course, back in 1970, the scientists and engineers put men on the moon using their slide rules with 3-decimal place accuracy...