我正在尝试打印具有不同小数点的多个双精度,我已经搜索了一段时间,但我无法找到适合我需要的确切解决方案。
让我举个例子来解释一下,这里有几个双变量:
1.23- 0.3301.001.001
我要的结果:
1.23- 0.33(删除不需要的0)
- 1(删除不需要的0) 1.001
是否有任何预先开发的语法,还是我必须自己做算法?
我当前的解决方案:
fun Double.roundToLastDecimal(): Number {
val num = this.toString().toDouble()
return if (num % 1 == 0.0) {
num.toInt()
} else {
num
}
}
Double.toString()
已经为您完成了大部分工作-它只保留必要的数字以区分数字和其他双倍数,因此它将去掉后面的零。
唯一的问题是希望1.0表示为1,因为这在技术上是整数表示,而不是双精度。您可以编写一个函数来处理这种情况:
// or a val with a get() to make the string representation a property
fun Double.roundToString() = when {
toInt().toDouble() == this -> toInt()
else -> this
}.toString()
仅供参考,如果数字足够小(小于10¯³),toString()
将生成科学记数法,而不是列出所有带前导零的数字。如果你想处理这些,你可能需要处理格式字符串,决定你想要多少精度,等等。
这里有一种方法可以做到这一点,最多10位精度,并删除任何尾随零(以及小数点本身,如果它结束在末尾):
fun Double.roundToString() = "%.10f".format(this).trimEnd('0').trimEnd('.')
或者使用正则表达式
fun Double.roundToString() = "%.10f".format(this).replace(Regex("\.*0+$"), "")
我会为Double
使用一个简单的扩展函数,也许像这样:
fun Double.printMinimalRepresentation() {
// check if the decimal places equal zero
if (this % 1 > 0.0) {
// if not, just print the number
println(this)
} else {
// otherwise convert to Int and print
println(this.toInt())
}
}
main
函数示例:
fun main() {
var a: Double = 1.23
var b: Double = 0.330
var c: Double = 1.00
var d: Double = 1.001
a.printMinimalRepresentation()
b.printMinimalRepresentation()
c.printMinimalRepresentation()
d.printMinimalRepresentation()
}
这个打印
1.23
0.33
1
1.001
请注意,转换toInt()
不仅删除了不需要的零,而且也删除了明显不需要的点。
val value = 0.330
val res = (value * 100.0).roundToInt()/100.0
您是否尝试过使用kotlin.math
包中的round
函数?
import kotlin.math.round