将Kotlin的Double舍入到小数点后一位:从0.044999到0.1 [英] Round Double to 1 decimal place kotlin: from 0.044999 to 0.1

查看:2551
本文介绍了将Kotlin的Double舍入到小数点后一位:从0.044999到0.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Double变量0.0449999,我想将其四舍五入到小数点后一位0.1.

I have a Double variable that is 0.0449999 and I would like to round it to 1 decimal place 0.1 .

我正在使用Kotlin,但是Java解决方案也很有帮助.

I am using Kotlin but the Java solution is also helpful.

val number:Double = 0.0449999

我尝试使用以下两种解决方案将小数点后一位:

I tried getting 1 decimal place with these two solutions:

  1. val solution = Math.round(number * 10.0) / 10.0
  2. val solution = String.format("%.1f", number)
  1. val solution = Math.round(number * 10.0) / 10.0
  2. val solution = String.format("%.1f", number)

问题是两种情况下我都得到0.0,因为它会将数字从0.04舍入到0.0.并不需要将所有的小数点都取整.

The problem is that I get 0.0 in both cases because it rounds the number from 0.04 to 0.0. It doesn't take all decimals and round it.

我想获得0.1:0.045 -> 0.05 -> 0.1

推荐答案

最后,我按照Andy Turner的建议进行了操作,四舍五入到小数点后三位,然后四舍五入到1,然后再四舍五入:

Finally I did what Andy Turner suggested, rounded to 3 decimals, then to 2 and then to 1:

答案1:

val number:Double = 0.0449999
val number3digits:Double = String.format("%.3f", number).toDouble()
val number2digits:Double = String.format("%.2f", number3digits).toDouble()
val solution:Double = String.format("%.1f", number2digits).toDouble()

答案2:

val number:Double = 0.0449999
val number3digits:Double = Math.round(number * 1000.0) / 1000.0
val number2digits:Double = Math.round(number3digits * 100.0) / 100.0
val solution:Double = Math.round(number2digits * 10.0) / 10.0

结果:

0.045→0.05→0.1

0.045 → 0.05 → 0.1

注意:我知道这不是应该如何工作的,但是有时在某些特殊情况下,您需要考虑所有小数点后四舍五入,因此也许有人觉得这很有用.

Note: I know it is not how it should work but sometimes you need to round up taking into account all decimals for some special cases so maybe someone finds this useful.

这篇关于将Kotlin的Double舍入到小数点后一位:从0.044999到0.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆