NSDecimalNumber zeros following decimal point (iPhone SDK)
Asked Answered
F

2

5

I have the following code

(...)
numberStyle = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                                                     scale:2
                                                          raiseOnExactness:NO
                                                           raiseOnOverflow:NO
                                                          raiseOnUnderflow:NO
                                                       raiseOnDivideByZero:NO];

strThree = textFieldThree.text;
strThree = [strThree stringByReplacingOccurrencesOfString:@"." withString:@""];

fieldOneDNa = (NSDecimalNumber *)[NSDecimalNumber decimalNumberWithString:strThree];
oneHundred = (NSDecimalNumber *)[NSDecimalNumber decimalNumberWithString:@"100"];
fieldOneDN = [fieldOneDNa decimalNumberByDividingBy:oneHundred
                                       withBehavior:numberStyle];

firstStepReturn = [fieldOneDN stringValue];
textFieldThree.text = firstStepReturn;
(...)

I would like to be able to have firstStepReturn have 2 digits following the decimal point even if they are .00 or .*0. For example, if 323.390 was inputted into the textfield "textFieldThree", it would be processed and returned to the textfield as 3233.90. At the moment, it is displaying as 3233.9.

Any help would be greatly appreciated.

Fraise answered 22/12, 2009 at 10:24 Comment(0)
S
18

NSDecimalNumber subclasses NSNumber so you just need to use NSNumberFormatter


 NSDecimalNumber * dn = [NSDecimalNumber decimalNumberWithString:@"1234.5"];
 NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
 [nf setMinimumFractionDigits:2];
 [nf setMaximumFractionDigits:2];
 NSString *ns  = [nf stringFromNumber:dn];

Simples

Swearword answered 24/12, 2009 at 19:37 Comment(1)
there is also help here #810661Swearword
S
4

Why not use textFieldThree.text=[NSString stringWithFormat:@"%.2f",[fieldOneDN floatvalue]];

(or something similar - sorry I'm on a PC right now so can't test this)

Swearword answered 22/12, 2009 at 17:6 Comment(1)
Thanks, but I was trying to avoid using a float because it was inaccurate when large numbers were used. Do you have any other suggestions?Fraise

© 2022 - 2024 — McMap. All rights reserved.