本文介绍了限制双到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何实现从双下面的转换为字符串:

  1.4324 => 1.43
9.4000 => 9.4
43.000 => 43

即。我要四舍五入到的小数位数,但不希望任何尾随零,也就是我不想

  9.4 => 9.40(错)
43.000 => 43.00(错)

所以这code,我现在不工作,因为它显示多余的零:

  [的NSString stringWithFormat:@%2F,总]


解决方案

使用NSNumberFormatter.见的格式化编程指南上Number格式化的。

How do I achieve the following conversion from double to a string:

1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"

i.e. I want to round to to decimal places but dont want any trailing zeros, ie i dont want

9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)

So this code which I have now doesn't work as it displays excess zeros:

[NSString stringWithFormat: @"%.2f", total]
解决方案

Use NSNumberFormatter. See the Data Formatting Programming Guide's chapter on Number Formatters.

这篇关于限制双到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 10:18
查看更多