DecimalFormat with RoundingMode.HALF_UP

前端 未结 2 614
名媛妹妹
名媛妹妹 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) {
        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")))
    }
    

提交回复
热议问题