math - 带 RoundingMode.HALF_UP 的 DecimalFormat

标签 math kotlin rounding number-formatting

有一个简单的代码

import java.math.RoundingMode
import java.text.DecimalFormat
  
fun main(args: Array<String>) {
  val f = DecimalFormat("#.##").apply { roundingMode = RoundingMode.HALF_UP }
  println(f.format(-0.025f))
  println(f.format(-0.015f))
  println(f.format(-0.005f))
  println(f.format(0.005f))
  println(f.format(0.015f))
  println(f.format(0.025f))
}

我得到以下输出:

-0,03 <-- ok

-0,01 <-- expecting -0,02

-0 <-- expecting -0,01

0 <-- expecting 0,01

0,01 <--- expecting 0,02

0,03 <-- ok

我是否正确理解了 RoundingMode.HALF_UP 的含义?

附注 我发现,使用 double 而不是 float 可以解决问题。因此 println(f.format(0.005.toDouble())) 有效,给出预期的 0.1

最佳答案

文档中关于 RoundingMode.HALF_UP 的内容是:

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

虽然这可能看起来像您正在寻找的行为,但这些是十进制 float ,并且它们很难在内存中表示。 the Oracle site 上有一篇很棒的读物。 .

因此,看起来 -0.005 和 -0.015 都比其他值更接近(最近的邻居)-0.01,因此它们都被格式化为 -0.01。要使您的代码执行您想要的操作,请将舍入模式更改为:

roundingMode = RoundingMode.UP

运行的输出是:

-0.03
-0.02
-0.01
0.01
0.02
0.03

这正是您所期望的。如果您确实希望代码正常工作,则可以使用以下方法:

import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat

fun main(args: Array<String>) {
    val f = DecimalFormat("#.##").apply { roundingMode = RoundingMode.HALF_UP }
    println(f.format( BigDecimal("-1000.045")))
    println(f.format( BigDecimal("-1000.035")))
    println(f.format( BigDecimal("-1000.025")))
    println(f.format( BigDecimal("-1000.015")))
    println(f.format( BigDecimal("-1000.005")))
}

关于math - 带 RoundingMode.HALF_UP 的 DecimalFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740617/

相关文章:

google-bigquery - 如何在 BigQuery 中将数值转换为货币?

math - 这里写的 R 符号是什么意思?

php - 如何在PHP中将数字除以没有余数?

algorithm - 大整数的除法(模数)(最多 200 位)

android - 为什么不调用 onConfigurationChanged?

c - 小数点后N位C四舍五入

java - 在Java中寻找多项式的根

kotlin - 如何在 KMP 公共(public)源集中使用通用 C/C++ 代码?

java - Kotlin:只有 getter 的私有(private)可变属性

java - 使用 BigDecimals 舍入区域