具有RoundingMode.HALF_UP的DecimalFormat [英] DecimalFormat with RoundingMode.HALF_UP

查看:229
本文介绍了具有RoundingMode.HALF_UP的DecimalFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有简单的代码

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<-好的

-0,03 <-- ok

-0,01<-预计-0,02

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

-0<-期望-0,01

-0 <-- expecting -0,01

0<-预期为0.01

0 <-- expecting 0,01

0,01< ---期望0,02

0,01 <--- expecting 0,02

0,03<-好的

0,03 <-- ok

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

Do I correctly understand RoundingMode.HALF_UP meaning?

PS 我发现,使用double代替float可以解决问题.因此println(f.format(0.005.toDouble()))起作用,给出预期的0.1.

P.S. I had found, that using doubles instead of floats solve the problem. So println(f.format(0.005.toDouble())) works, giving expected 0.1.

推荐答案

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

除非两个邻居都是等距的,否则舍入模式将朝最近的邻居"舍入.

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

虽然看起来像您想要的行为,但它们是十进制浮点数,它们很难在内存中表示出来.在 Oracle站点上有很多读物.

While that might look like the behavior you're looking for, these are decimal floats, and they have a hard time being represented in memory. There's a great read on it on the Oracle site.

因此,似乎-0.005和-0.015都比其他任何东西都更接近(最近的邻居)-0.01,因此它们的格式都设置为-0.01.要使您的代码执行您想要的操作,就是将舍入模式更改为:

So, it seems that -0.005 and -0.015 both are closer (nearest neighbor) to -0.01 than anything else, so they both are formatted as -0.01. To make your code do what you want it do to, is to change your rounding mode to:

roundingMode = RoundingMode.UP

运行的输出为:

-0.03
-0.02
-0.01
0.01
0.02
0.03

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

Which is exactly what you expected. If you do want your code to work, you can use the following approach though:

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")))
}

这篇关于具有RoundingMode.HALF_UP的DecimalFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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