Objective-C:精确到3个小数 [英] Objective-C: Flooring to 3 decimals correctly

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

问题描述

我正在尝试将浮点值设置为小数点后第三位.例如,值2.56976应该是2.569而不是2.570.我搜索并找到了类似这样的答案:

I am trying to floor a float value to the third decimal. For example, the value 2.56976 shall be 2.569 not 2.570. I searched and found answers like these:

底数乘小数位

这样的答案是不准确的.例如代码:

Such answers are not accurate. For example the code:

double value = (double)((unsigned int)(value * (double)placed)) / (double)placed

可以返回value - 1,这是不正确的.值和放置的value * (double)placed)的乘积可能会引入类似以下内容:2100.999999996.当更改为unsigned int时,它变成2100,这是错误的(正确的值应为2101).其他答案也遇到同样的问题.在Java中,您可以使用BigDecimal保存所有麻烦.

can return the value - 1 and this is not correct. The multiplication of value and placed value * (double)placed) could introduce something like: 2100.999999996. When changed to unsigned int, it becomes 2100 which is wrong (the correct value should be 2101). Other answers suffer from the same issue. In Java, you can use BigDecimal which saves all that hassels.

(注意:当然,对2100.9999进行四舍五入不是一种选择,因为它破坏了将底线的整个概念破坏为正确地为3个小数")

(Note: of course, rounding the 2100.9999 is not an option as it ruins the whole idea of flooring to "3 decimals correctly")

推荐答案

我不得不考虑一个涉及NSString的解决方案,它的工作原理很吸引人.这是完整的方法:

I had to consider a solution involving NSString and it worked like a charm. Here is the full method:

- (float) getFlooredPrice:(float) passedPrice {

    NSString *floatPassedPriceString = [NSString stringWithFormat:@"%f", passedPrice];
    NSArray *floatArray = [floatPassedPriceString componentsSeparatedByString:@"."];
    NSString *fixedPart = [floatArray objectAtIndex:0];
    NSString *decimalPart = @"";
    if ([floatArray count] > 1) {
        NSString *decimalPartWhole = [floatArray objectAtIndex:1];
        if (decimalPartWhole.length > 3) {
            decimalPart = [decimalPartWhole substringToIndex:3];
        } else {
            decimalPart = decimalPartWhole;
        }
    }
    NSString *wholeNumber = [NSString stringWithFormat:@"%@.%@", fixedPart, decimalPart];

    return [wholeNumber floatValue];

}

这篇关于Objective-C:精确到3个小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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