将双精度数限制为两位小数 [英] Limit a double to two decimal places

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

问题描述

如何实现以下从双精度到字符串的转换:

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]

推荐答案

使用 NSNumberFormatter.请参阅 数据格式化编程指南 的关于 数字格式化程序.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆