Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round double value to 2 decimal places

I have a double value as 22.368511 I want to round it to 2 decimal places. i.e. it should return 22.37

How can I do that?

like image 494
copenndthagen Avatar asked Feb 13 '11 17:02

copenndthagen


People also ask

How do you round a double to two decimal places in C#?

double inputValue = 48.00; inputValue = Math. Round(inputValue, 2); will result 48 only.

How do you truncate a double to two decimal places?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.


1 Answers

As in most languages the format is

%.2f 

you can see more examples here


Edit: I also got this if your concerned about the display of the point in cases of 25.00

{     NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];     [fmt setPositiveFormat:@"0.##"];     NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);     NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);     NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]); } 
2010-08-22 15:04:10.614 a.out[6954:903] 25.34 2010-08-22 15:04:10.616 a.out[6954:903] 25.3 2010-08-22 15:04:10.617 a.out[6954:903] 25 
like image 53
Jason Rogers Avatar answered Oct 13 '22 09:10

Jason Rogers