Having a simple code
import java.math.RoundingMode
import java.text.DecimalFormat
fun main(args: Array) {
val f = DecimalFormat("#.##"
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")))
}