NSNumberFormatter舍入为负零

NSNumberFormatter舍入为负零

本文介绍了NSNumberFormatter舍入为负零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NSNumberFormatter 将浮点值格式化为整数字符串,即省略小数部分。我觉得很奇怪,范围为(-0.5,0) 的数字最终为 -0 。由于此值将显示给用户,因此我认为负零是不合适的。我尝试了 numberStyle roundingMode 的各种组合,但均未成功。

I'm using NSNumberFormatter to format float values as integer strings, i.e. omitting the fractional part. I find it odd, that numbers in range (-0.5, 0) end up as -0. As this value will be displayed to the user, I think that negative zero is not appropriate. I have experimented with various combinations of numberStyle and roundingMode without success.

是否可以将 NSNumberFormatter 配置为将其输出为 0 ,还是我必须求助于手动校正该范围?

Is there a way to configure the NSNumberFormatter to output them as 0, or do I have to resort to manual correction for that range?

推荐答案

我必须自己对此进行校正。我正在使用NSNumberFormatter以默认的 numberStyle 显示温度— NSNumberFormatterNoStyle 将数字四舍五入为整数, roundingMode 设置为 NSNumberFormatterRoundHalfUp 。最后,我确实截取了有问题的范围内的值并自行四舍五入:

I had to do correct this myself. I am using the NSNumberFormatter to display temperature with default numberStyleNSNumberFormatterNoStyle which rounds the numbers to the whole integer, roundingMode set to NSNumberFormatterRoundHalfUp. In the end I did intercept the values in problematic range and round it myself:

- (NSString *)temperature:(NSNumber *)temperature
{
    float f = [temperature floatValue];
    if (f < 0 && f > -0.5)
        temperature = [NSNumber numberWithLong:lround(f)];

    return [self.temperatureFormatter stringFromNumber:temperature];
}

这篇关于NSNumberFormatter舍入为负零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:42