Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set floating point precision inside a variable

I am currently working a program where I need to calculate a rounded value to only 2 digits after a floating point. Say, I have declared

float a;

If a = 3.555 then it would store a = 3.56, rounding up.

For a = 3.423, the value of a would be a = 3.423, no change.

I can do this to print output, but what I need to do when storing it into a variable and use that variable for some other calculation?

like image 896
shushu Avatar asked Jun 06 '26 00:06

shushu


1 Answers

If you need two digits after the decimal point, don't use floating point. Use a fixed point number instead. For example, just use an integer that's 100 times larger than the decimal number you want to represent. Trying to fit a base 2 floating point number into rounding rules like this just isn't going to produce satisfactory results for you.

like image 76
Mark B Avatar answered Jun 07 '26 14:06

Mark B