Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

kotlin - 使用无法在Kotlin中使用的格式对数字进行四舍五入(Round a Number using format not working in Kotlin)

I used String.format() to round to the third decimal place.

(我使用String.format()舍入到小数点后三位。)

However this didn't work and I solved it using DecimalFormat .

(但是,这不起作用,我使用DecimalFormat解决了它。)

Is there anything I implemented wrong?

(我有实施错误的地方吗?)

val value = 23.695f
Timber.e("format: ${"%.2f".format(value)}")

Expect : 23.70

(期望 :23.70)

Result : 23.69

(结果 :23.69)

  ask by pistolcaffe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your string formatting example you're not rounding the number you're just taking the first two decimal places.

(在您的字符串格式示例中,您没有舍入仅将小数点后两位放在首位的数字。)

So your code drops the .005 and keeps the .69

(因此,您的代码会删除.005并保留.69)

If .70 is the desired result then DecimalFormat sounds correct to me

(如果.70是所需的结果,那么DecimalFormat对我来说听起来正确)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...