本文探討了在 Kotlin 中舍入具有 2 個小數位的浮點數或雙精度數的不同方法。
1.使用 roundToInt()
功能
這 roundToInt()
函數將 double 值四捨五入到最接近的整數。它可以按如下方式使用所需的小數位四捨五入浮點數或雙精度數。
1 2 3 4 5 6 7 8 9 |
import kotlin.math.roundToInt fun main() { val random = 0.8458215996440445 val roundoff = (random * 100.0).roundToInt() / 100.0 println(roundoff) // 0.85 } |
0 的數量表示輸出中的小數位數。因此,要保留 4 位小數,使用 value 10000.0
:
1 2 3 4 5 6 7 8 9 |
import kotlin.math.roundToInt fun main() { val random = 0.037854093052263726 val roundoff = (random * 10000.0).roundToInt() / 10000.0 println(roundoff) // 0.0379 } |
此外,請考慮上述代碼的替代和等效版本:
1 2 3 4 5 6 7 8 9 |
import kotlin.math.roundToInt fun main() { val random = 0.797490220519589 val roundoff = (random * 10000).roundToInt().toDouble() / 10000 println(roundoff) // 0.7975 } |
值得注意的是,浮點運算非常棘手,可能並不總是按預期工作。例如,值 295.335
被“向下”四捨五入到 295.33
而不是四捨五入 295.34
.
1 2 3 4 5 6 7 8 |
import kotlin.math.roundToInt fun main() { val random = 295.335 println(random * 100.0) // 29533.499999999996 println((random * 100.0).roundToInt() / 100.0) // 295.33 } |
2.使用 DecimalFormat.format()
功能
或者,我們可以調用 DecimalFormat.format()
使用模式將雙精度數限制為 2 位小數點的功能 #.##
.這 RoundingMode
可以使用 setRoundingMode()
功能。
1 2 3 4 5 6 7 8 9 10 11 |
import java.math.RoundingMode import java.text.DecimalFormat fun main() { val random = 8435.21057752090819915 val df = DecimalFormat("#.##") df.roundingMode = RoundingMode.DOWN val roundoff = df.format(random) println(roundoff) // 8435.21 } |
請注意,數量 #
後面的點表示小數位數。因此,要保留 3 位小數,請使用模式 #.###
:
1 2 3 4 5 6 7 8 9 10 11 |
import java.math.RoundingMode import java.text.DecimalFormat fun main() { val random = 4732.8326486752163523 val df = DecimalFormat("#.###") df.roundingMode = RoundingMode.DOWN val roundoff = df.format(random) println(roundoff) // 4732.832 } |
此解決方案面臨與 roundToInt()
如果沒有提供舍入模式,則函數。即,價值 295.335
被“向下”四捨五入到 295.33
而不是四捨五入 295.34
.
1 2 3 4 5 6 7 8 9 |
import java.text.DecimalFormat fun main() { val random = 295.335 val df = DecimalFormat("#.##") val roundoff = df.format(random) println(roundoff) // 295.33 } |
3.使用 String.format()
功能
我們也可以使用 String.format()
函數用特定的小數位數四捨五入浮點數或雙精度數。這適用於價值 295.335
, 如下所示:
1 2 3 4 5 |
fun main() { val random = 295.335 val roundoff = String.format("%.2f", random) println(roundoff) // 295.34 } |
4.使用 BigDecimal
最後,我們可以將 double 值轉換為 BigDecimal
並使用 setScale()
指定的函數 RoundingMode
.
1 2 3 4 5 6 7 8 9 |
import java.math.BigDecimal import java.math.RoundingMode fun main() { val random = Math.random() val bd = BigDecimal(random) val roundoff = bd.setScale(2, RoundingMode.FLOOR) println(roundoff) } |
這就是在 Kotlin 中將浮點數或雙精度數四捨五入,小數點後 2 位。