本文介绍了将float截断为2个小数位的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,有没有一种方法可以将浮点数截断为2个小数,以便您可以用它执行进一步的计算?我见过的所有线程都涉及到强制转换为字符串,我无法弄清楚如何在数学上使用它.

In Swift, is there a way to truncate a float to 2 decimals, such that you can perform further calculations with it? All of the threads I've seen deal with casting to a string, which I can't figure out how to then use mathematically.

我尝试使用扩展程序(在此论坛上找到),认为我可以在截断后将其转换为浮点数,但最终以另一个未截断的浮点数开始了我的工作.我需要将返回值设置为四分之一步(即6.50、6.75、5.25等),最终得到的结果应该是6.990022....

I tried using an extension (found on this forum), figuring I could cast back to float after the truncation, but I end up where I started, with another, non-truncated float. I need my return value to be in quarter steps (i.e. 6.50, 6.75, 5.25, etc), and what I'm ending up with, are results like 6.990022....

必须有一种简单的方法来执行此操作,但是我碰壁了.预先感谢...

There has to be a simple way to do this, but I'm hitting a wall. Thanks in advance...

问题出在这里:

func roundToNearestQuarter(#power : Float) -> String {

     var errorToLowerQuarterRaw : Float = power % 0.25  // 0.210000038146973

     var errorToLowerQuarterString = errorToLowerQuarterStepRaw.string(2)  // "0.21"

     var errorToLowerQuarter = NSString(string: errorToLowerQuaterStepString).floatValue  // 0.209999993443489

// more code

}

roundToNearestQuater(6.71)

推荐答案

不能FloatDouble精确舍入到2个十进制数字 .原因是这些数据类型使用二进制浮点表示形式,并且不能精确表示0.1或0.01之类的数字.例如参见

You cannot round a Float or Double to 2 decimal digits exactly.The reason is that these data types use a binary floating point representation,and cannot represent numbers like 0.1 or 0.01 exactly.See for example

  • Why Are Floating Point Numbers Inaccurate?
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic

但是你说:

以及完全可能,因为0.25 = 2 可以精确地表示为浮点数.

and that is exactly possible because 0.25 = 2 can be represented exactly as a floating point number.

round()函数将浮点数四舍五入为最接近的整数值.要四舍五入到最接近的四分之一,您只需使用因子4缩放"计算即可:

The round() function rounds a floating point number to the nearest integral value.To round to the nearest quarter, you just have to "scale" the calculation with the factor 4:

func roundToNearestQuarter(num : Float) -> Float {
    return round(num * 4.0)/4.0
}

roundToNearestQuarter(6.71) // 6.75
roundToNearestQuarter(6.6)  // 6.5

这篇关于将float截断为2个小数位的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:55