Easiest way to truncate float to 2 decimal places?

前端 未结 2 674
滥情空心
滥情空心 2021-01-18 02:03

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 str

2条回答
  •  旧时难觅i
    2021-01-18 02:54

    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

    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
    

提交回复
热议问题