Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncating double without rounding in C

Tags:

c++

c

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)

like image 814
Coder Avatar asked Mar 31 '10 20:03

Coder


People also ask

How do I make my C not round?

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.

Does truncation always round down?

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.

Does toFixed round or truncate?

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.


2 Answers

#include <math.h>
...
    printf("%.2f", floor(100 * R) / 100);
like image 95
Hans Passant Avatar answered Oct 25 '22 14:10

Hans Passant


All you have to do is subtract .005 from the number and magically printf will behave as you wish: always round down.

like image 45
frankc Avatar answered Oct 25 '22 14:10

frankc