Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding off decimal fraction in ios

NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
NSString *temp = [format stringFromNumber:[NSNumber numberWithFloat:23.4451]];
NSLog(@"%@",temp);

I need round off a six decimal fraction number to two decimal. In iOS I tried the code above. I get the answer 23.5 when I give input as 23.45, but when I give input 23.445 the answer is 23.44.

Could someone clear-up "round half up" in iOS.

like image 557
karan Avatar asked Sep 06 '12 05:09

karan


People also ask

How do you change a fraction to rounded decimal?

The fraction 1/4 becomes 1 ÷ 4. Complete the division to convert the fraction to a decimal. You can reduce the fraction to lowest terms first to make the long division math a bit easier. For example, 9/12 = 9 ÷ 12 = 0.75.

How do you round a decimal in Swift?

Rounding Numbers in Swift By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do you use decimal on iPhone?

Here's a longer answer: on an iPhone, you enter decimals by pressing the +*# button in the lower-left corner of the keypad and pressing either * or #.


1 Answers

Interestingly, well at least to me, it is a float precision issue. As rdelmar had suggested in comments.

This problem can be avoided, at least at this precision level, by using a double. For example:

NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
[format setMinimumFractionDigits:2];

// With Float:
NSLog(@"%@",[format stringFromNumber:[NSNumber numberWithFloat:23.445]]); // Float
// Logs 23.44
NSLog(@"%@",[format stringFromNumber:[NSNumber numberWithDouble:23.445]]); // Double
// Logs 23.45

So you were not suffering from bad code, just imprecise variables.

like image 106
NJones Avatar answered Sep 20 '22 23:09

NJones