英文:
Print float with two decimals unless number is a mathematical integer
问题
有没有一种简单的方法将浮点值打印为带小数的字符串,如果该值有小数,则像没有小数的整数一样打印?
12.5 打印为 12.50
15.0 打印为 15
有没有一种简单的方法可以做到这一点?我可以想到的方法包括将浮点数解析为字符串再转换为整数,但这似乎不是最优解。
编辑:这个答案不满足我的要求:https://stackoverflow.com/questions/11826439/show-decimal-of-a-double-only-when-needed
这个答案只在值只有一个小数位时显示一个小数位。我需要的是显示两个小数位,或者什么都不显示。
英文:
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
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.
EDIT: This answer does not do what I want: https://stackoverflow.com/questions/11826439/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.
答案1
得分: 3
你可以使用 String.format()
函数,并且如果是 .00
,可以使用 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
这样的四舍五入的数字。
英文:
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())
}
Prints:
12.50
15
This also works with rounded numbers such as 12.999
etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论