如何实现从双精度到字符串的以下转换:
1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"我想四舍五入到小数点后几位,但不想要尾随的零
9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)所以我现在的这段代码不能工作,因为它显示了多余的零:
[NSString stringWithFormat: @"%.2f", total]发布于 2009-07-11 10:26:16
发布于 2010-08-30 20:43:21
你犯了个简单的错误。这将会起作用:
[NSString stringWithFormat: @"%.2lf", total]发布于 2009-07-11 11:19:50
最简单的方法可能是滚动您自己的。我以前不得不用C语言来做这件事,因为没有办法用printf格式化得到你想要的行为。
这在Objective-C中似乎也不是很容易。我会试一试:
NSString *ftotal = [NSString stringWithFormat: @"%.2f", total];
while ([ftotal hasSuffix:@"0"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}
if ([ftotal hasSuffix:@"."]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}或者这个(可能更快)变体:
NSString *ftotal = [NSString stringWithFormat: @"%.2f", total];
if ([ftotal hasSuffix:@".00"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-3];
} else {
if ([ftotal hasSuffix:@"0"]) {
ftotal = [ftotal subStringToIndex [ftotal length]-1];
}
}stringWithFormat保证末尾总是有一个".nn" (其中n是一个数字字符)。while和if只需去掉尾随的零和尾随的小数(如果它是整数)。
显然,您可能希望将它放在一个函数或类中,这样您就可以从任何地方访问它,而不必到处重复代码。
https://stackoverflow.com/questions/1113408
复制相似问题