限制小数点到需要的 [英] Limiting decimal points to what is needed

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

问题描述


可能重复:

舍入数字

目标-C:如何在float中截断额外的零?

更正浮点数

在Objective C中,我有一个双倍的数字,得到如下计算的答案:

In Objective C, I have a double which receives the answer to a calculation as shown:

double answer = a / b;

双变量有时可以是一个整数,但也可以是一个例子,例如

The double variable can sometimes be a whole integer but can also be a fraction e.g.

NSLog(@"%f", answer)

这可以返回2.000000或5.142394或2.142000。

This can return 2.000000 or 5.142394 or 2.142000.

我想知道是否有方法来编辑小数位,使尾随0的是不可见的例如:

I was wondering if there was a way to edit the decimal places so that the trailing 0's are not visible for example:

2.000000将是2

5.142394将是5.142394

2.142000将是2.142

2.000000 would be 2
5.142394 would be 5.142394
2.142000 would be 2.142

如何做?

推荐答案

如果你愿意要硬编码你以后的小数位数,这将给你两位小数:

If you'd like to hard-code the number of decimal places you're after, this would give you two decimal places:

NSLog(@"%.2f", answer);

详细了解格式说明符:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

或者,如果您想要即时更改小数位数,请考虑使用 NSNumberFormatter 类:

Alternatively, if you'd like to change the number of decimal places on-the-fly, consider using the NSNumberFormatter class:

int maxDigitsAfterDecimal = 3; // here's where you set the dp

NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setMaximumFractionDigits:maxDigitsAfterDecimal];

NSString * trimmed = [nf stringFromNumber:[NSNumber numberWithDouble:3.14159]];
NSLog(@"%@", trimmed); // in this case, 3.142

[nf release];

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

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