您好,我需要在模拟ROUND()函数中将0.5变为0. 例如0.4->0;9.5->9;10.6->11

我也在试着做

     var height = Math.round(width / firstNum * thecondNum).toInt()
    var e = height.toDouble()
    var roundedHalfDown = e.toBigDecimal().setScale(0, ROUND_HALF_DOWN).toDouble().toInt()

  
    return ("$width x $roundedHalfDown").replace(" ","")
}

我也试过这个

 var height = Math.round(width / firstNum * thecondNum).toInt()
    var e = height.toDouble()
    var r = Math.floor(e)
    if ((height % 10) == 5){
        
      r -= 1
        return ("$width x $r").replace(" ","")
    }
    
    else return ("$width x $height").replace(" ","")
}

测试结果显示 4:3,宽度=1457预期:<1457x109[2]>但实际为:<1457x109[3]>

推荐答案

对于给定的输入,您的第一个建议通过setScale起作用,不需要BigDecimal的输出上的中间toDouble():

fun Double.roundDown() = toBigDecimal().setScale(0, RoundingMode.HALF_DOWN).toInt()
fun testOutput(input: Double) = 
  println("%.4f rounded to %d".format(input, input.roundDown()))

testOutput(0.4)    // 0.4000 rounded to 0
testOutput(9.4999) // 9.4999 rounded to 9
testOutput(9.5)    // 9.5000 rounded to 9
testOutput(9.5001) // 9.5001 rounded to 10
testOutput(10.6)   // 10.600 rounded to 11

Kotlin相关问答推荐

等待下一个值时暂停Kotlin Coroutine

如何确保Kotlin子类已完成初始化?

在Kotlin中将String转换为T

处理合成层次 struct 中的深层按钮以切换视图

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

通用接口继承

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

Kotlin SAM/功能接口抛出 AbstractMethodError

如何在 Compose 中创建可重用的修饰符?

如何修复 ViewPager2 中的Design assumption violated错误?

Kotlin 是如何编译的?

Kotlin - 覆盖方法中的 IllegalArgumentException

无法为 retrofit2.Call 调用无参数构造函数

Intellij 显示 build.gradle.kts 中的每一行都是红色的

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

Kotlin,什么时候按map授权?

如何修复未解析的参考生命周期范围?

Kotlin for assertThat(foo, instanceOf(Bar.class))