DecimalFormat with RoundingMode.HALF_UP

前端 未结 2 569
名媛妹妹
名媛妹妹 2021-01-27 01:01

Having a simple code

import java.math.RoundingMode
import java.text.DecimalFormat
  
fun main(args: Array) {
  val f = DecimalFormat("#.##"         


        
相关标签:
2条回答
  • 2021-01-27 01:33

    What the documentation says about RoundingMode.HALF_UP is:

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

    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.

    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
    

    The output of running that is:

    -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")))
    }
    
    0 讨论(0)
  • 2021-01-27 01:35

    Never ever use float or double if you want exact numbers to show up. If you round and want the rounding to happen on a solid base, you don't want float or double neither ;-)

    Your sample using double would also give wrong results. Your sample using BigDecimal will give the results you expect. So... stick with BigDecimal if you want to be safe(r).

    fun main(args: Array<String>) {
      val f = DecimalFormat("#.##").apply { roundingMode = RoundingMode.HALF_UP }
      println(f.format(BigDecimal("-0.025")))
      println(f.format(BigDecimal("-0.015")))
      println(f.format(BigDecimal("-0.005")))
      println(f.format(BigDecimal("0.005")))
      println(f.format(BigDecimal("0.015")))
      println(f.format(BigDecimal("0.025")))
    }
    
    0 讨论(0)
提交回复
热议问题