How to truncate decimals to x places in Swift

前端 未结 9 1945
Happy的楠姐
Happy的楠姐 2020-12-04 01:26

In my swift program, I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the

9条回答
  •  再見小時候
    2020-12-04 02:06

    I figured this one out.

    Just floor (round down) the number, with some fancy tricks.

    let x = 1.23556789
    let y = Double(floor(10000*x)/10000) // leaves on first four decimal places
    let z = Double(floor(1000*x)/1000) // leaves on first three decimal places
    print(y) // 1.2355
    print(z) // 1.235
    

    So, multiply by 1 and the number of 0s being the decimal places you want, floor that, and divide it by what you multiplied it by. And voila.

提交回复
热议问题