我有以下代码
(...)
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;
(...)
我希望firstStepReturn在小数点后面有2位数,即使它们是.00或。* 0。例如,如果323.390被输入到文本字段“textFieldThree”中,它将被处理并返回到文本字段3233.90。目前,它显示为3233.9。
非常感谢任何帮助。
答案 0 :(得分:18)
NSDecimalNumber子类NSNumber所以你只需要使用NSNumberFormatter
NSDecimalNumber * dn = [NSDecimalNumber decimalNumberWithString:@"1234.5"];
NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setMinimumFractionDigits:2];
[nf setMaximumFractionDigits:2];
NSString *ns = [nf stringFromNumber:dn];
Simples
答案 1 :(得分:4)
为什么不使用textFieldThree.text=[NSString stringWithFormat:@"%.2f",[fieldOneDN floatvalue]];
(或者类似的东西 - 抱歉我现在正在电脑上,所以无法测试这个)