How to avoid rounding off in NSNumberFormatter
Asked Answered
S

5

12

I am trying to have a number string with maximum 2 decimals precision, while rest decimals just trimmed off instead of rounding them up. For example:

I have: 123456.9964

I want: 123456.99 -> Just want to trim rest of the decimal places

What I have tried is:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat: 123456.9964]];
 NSLog(@"%@", numberAsString);

There is nothing to set rounding mode as "none". What else can I do to maintain Decimal style formatting along with trimmed decimal digits? Any help will be appreciated. Thanks.

Scrounge answered 7/3, 2013 at 5:54 Comment(0)
P
22

The following works for me:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
// optional - [numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
NSNumber *num = @(123456.9964);
NSString *numberAsString = [numberFormatter stringFromNumber:num];
NSLog(@"%@", numberAsString);

The output is: 123,456.99

Part of your problem is the use of numberWithFloat: instead of numberWithDouble:. Your number has too many digits for float.

Poplin answered 7/3, 2013 at 6:34 Comment(0)
N
1

you can use this

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble: 123456.9964]];
NSLog(@"%@", numberAsString);
Neoplasty answered 7/3, 2013 at 6:35 Comment(0)
L
0
[numberFormatter setRoundingMode: NSNumberFormatterRoundDown];

Use this code.

Linolinocut answered 7/3, 2013 at 6:6 Comment(3)
Not working. I am getting output as: 123457 while I want 123456.99Scrounge
@AnumAmin What is you also specify minimum fraction digits of 2?Poplin
@maddy if I specify min fractions as 2 (which is my requirement), I still get 123457.00Scrounge
B
0

In Swift 5:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
print(formatter.string(from: NSNumber(25.99))!)

prints 25.99

Bludge answered 15/4 at 19:11 Comment(0)
F
-1

you can also just use round() and then convert it into a string afterward

var y = round(100 * 123456.8864) / 100

var x:String = String(format:"%.2f", y)
println("x: \(x)")

would print x: 123456.89, rounding the 8 to a 9.

Flor answered 5/4, 2015 at 15:24 Comment(1)
whoops! forgot about the no rounding part.Flor

© 2022 - 2024 — McMap. All rights reserved.