Kotlin - 如何消除除前两位之外的小数

问题描述 投票:0回答:2

我想要实现的是保留 2 位小数并消除任何多余的小数,例如不进行任何舍入

3.556664 至 3.55(不四舍五入)

我尝试了以下方法

    "%.2f".format(3.556).toFloat() // the result is 3.56
    DecimalFormat("#.##").format(3.556).toFloat() // the result is 3.56
    BigDecimal(3.556).setScale(2, RoundingMode.DOWN).toFloat() // the result is 3.56
kotlin math decimal
2个回答
6
投票
val x = Math.floor(3.556 * 100) / 100 // == 3.55

Math.floor 返回小于或等于参数的值并且 等于一个数学整数。

在我们的例子中,3.556 * 100 = 355.6,下限为 355.0,因此 355/100 = 3.55


3
投票

您可以在 DecimalFormat 上设置舍入模式:

DecimalFormat("#.##")
    .apply { roundingMode = RoundingMode.FLOOR }
    .format(3.556)

但是,请注意,Float 实际上并不以十进制(以 10 为基数)存储数字,因此对于需要具有特定小数位数的数字来说,它不是合适的格式。当你将其转换为String时,你可能会发现小数位数发生了变化。为了确保特定的小数位数,您需要 BigDecimal。

© www.soinside.com 2019 - 2024. All rights reserved.