Lets consider we have a double R = 99.999999;
(which may be obtained by a result of some other computation),now the desired output is 99.99
I tried using printf("%.2lf",R);
but it's rounding off the value.How to get the desired output ? (preferably using printf
)
Printf is supposed to round it. To prevent this, truncate the argument to 4 decimal places. You could sprintf() into a temp buffer for 5 decimal places and then lop off the last digit. Or, you could multiply the source number by 10,000, cast it to an int, and then back to a float and divide by 10,000.
To round down, the formula is =ROUNDDOWN(num,digits) . When Excel truncates, it chops off part of the entered number and performs no rounding at all. So if you input 345.679 and format the number for no decimal points, it cuts off the digits after the decimal point.
toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
#include <math.h>
...
printf("%.2f", floor(100 * R) / 100);
All you have to do is subtract .005 from the number and magically printf will behave as you wish: always round down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With