除非数字是数学整数,否则以两位小数打印浮点数 [英] Print float with two decimals unless number is a mathematical integer
问题描述
是否有一种简单的方法将浮点值打印为带小数的字符串,如果该值具有小数,否则明智地将其打印为没有小数的int?
Is there a simple way of printing a floating value as a string with decimals if the value has decimals, other wise print it like an int without decimals?
12.5 would print 12.50
15.0 would print 15
有没有简单的方法可以做到这一点?我可以想到的方法包括将float解析为字符串到int,但这似乎不是最佳方法.
Is there a simple way to do this? I can think of ways which includes parse floats to strings to ints but it doesn't seem optimal.
This answer does not do what I want: Show decimal of a double only when needed
如果值只有一个小数,则此答案仅显示一个小数.我需要的是两位小数,或者什么都没有.
This answers only shows one decimal if the value only has one decimal. What I need is two decimals, or nothing.
推荐答案
您可以使用 String.format()
,如果用
You can use String.format()
, and strip off the decimal if it's .00
with removeSuffix()
:
fun Double.toMyFormat(): String =
String.format("%.2f", this).removeSuffix(".00")
fun main() {
println(12.5.toMyFormat())
println(15.0.toMyFormat())
}
打印:
12.50
15
这也适用于四舍五入的数字,例如12.999
等.
This also works with rounded numbers such as 12.999
etc.
这篇关于除非数字是数学整数,否则以两位小数打印浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!