DecimalFormat with RoundingMode.HALF_UP

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

提交回复
热议问题