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.
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.
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.
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 #.
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.
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