Easiest way to truncate float to 2 decimal places?

孤街浪徒 提交于 2019-12-01 16:48:32
Martin R

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

But you said:

I need my return value to be in quarter steps (i.e. 6.50, 6.75, 5.25, etc),

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

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
RGood

If you need to work with true precision (for currency-related applications, for example), you will probably want to use NSDecimalNumber instead of floating point.

The above approach can be applied to NSDecimalNumbers as shown below. In this example, the "step" that you are rounding to can be anything you choose, just set "increment" accordingly.

let number: NSDecimalNumber = 100.52
let increment: NSDecimalNumber = 0.25

let handler = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundBankers, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)     // Rounds to the nearest whole number
let result = number.decimalNumberByDividingBy(increment).decimalNumberByRoundingAccordingToBehavior(handler).decimalNumberByMultiplyingBy(increment)

For more on rounding with NSDecimalNumber see here: How to round an NSDecimalNumber in swift?

And yes, working with NSDecimalNumber is a terribly verbose way to do math, but it's not complicated. If you find yourself doing a project involving them frequently, I recommend you consider setting up Swift operator extensions so you can manipulate them in a more elegant way. Check out here for a nice example: https://gist.github.com/mattt/1ed12090d7c89f36fd28

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!