NSNumberFormatter 和舍入百分比值
这是我的代码片段,我不知道如何舍入双数。
double m = [tmpProduct.msrp doubleValue] ;
double d = [tmpProduct.discountPrice doubleValue];
double p = (d * 100 ) / m;
这里 tmpProduct.msrp 和 mpProduct.discountPrice 是 (NSDecimalNUmber *)
来自上面的操作我得到 p = 44.995757
我想将其转换为 (45%) ,我该怎么做?
这是我使用的,但这没有帮助。
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
[formatter stringFromNumber:[NSNumber numberWithDouble:p]]
here is my code snip, i dont know how to round double numbers.
double m = [tmpProduct.msrp doubleValue] ;
double d = [tmpProduct.discountPrice doubleValue];
double p = (d * 100 ) / m;
here tmpProduct.msrp and mpProduct.discountPrice are (NSDecimalNUmber *)
from the operation above I got p = 44.995757
i want to convert it to (45%) , how do i do that?
here is what i use , but that does not help.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
[formatter stringFromNumber:[NSNumber numberWithDouble:p]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过使用 NSDecimalNumber 提供的算术运算?
我自己没有尝试过,但似乎您通过在数字实例的双值上使用标准运算符(*、/、...)来绕过 NSDecimalNumber 的优点。
看看 NSDecimalNumber:执行算术
由于 Objective-C 不支持运算符重载,您将不得不使用以下方法:
更新:
使用 NSDecimalNumber 进行除法:
通过使用
descriptionWithLocale:
,您将得到正确的NSLocaleDecimalSeparator
更新 2:
我忘记了四舍五入:
NSDecimalNumber 支持多种舍入模式。
阅读
decimalNumberByRoundingAccordingToBehavior:
Have you tried using the arithmetic operations NSDecimalNumber provides?
I haven't tried that myself, but it seems you are bypassing the advantages of NSDecimalNumber by using standard operators ( *, /, ...) on the double values of your number instances.
Take a look at NSDecimalNumber: Performing Arithmetic
As Objective-C does not support operator overloading you will have to use methods such as:
Update:
Division using NSDecimalNumber:
by using
descriptionWithLocale:
, you get the correctNSLocaleDecimalSeparator
Update 2:
I forgot about the rounding:
NSDecimalNumber supports several rounding modes.
Read the documentation of
decimalNumberByRoundingAccordingToBehavior:
在这种特定情况下,我建议将样式设置为 NSNumberFormatterPercentStyle 并将最大小数位数设置为 0。这样您就不必担心舍入问题。这对我有用:
这给出了字符串“45%”。
In this specific case, I'd suggest setting the style to NSNumberFormatterPercentStyle and the maximum fraction digits to 0. Then you shouldn't have to worry about the rounding. This works for me:
This gives the string "45%".