Home > Software engineering >  BigDecimal - too many leading zeros in fraction part
BigDecimal - too many leading zeros in fraction part

Time:08-04

I wish to sum up two numbers. They are BigDecimals.

n1 = 0.0000000040.toBigDecimal() 
n2 = 0.0000000030.toBigDecimal() 
println(n1   n2) //result: 7.0E-9

How can I fix it to get the result 0.0000000070 as BigDecimal?

CodePudding user response:

Try

println((n1   n2).toPlainString())

CodePudding user response:

You can use string format to have the desired output.

val n1 = 0.0000000040.toBigDecimal()
val n2 = 0.0000000030.toBigDecimal()

// addition of BigDecimals
val n3 = n1   n2 
val n4 = n1.add(n2)

// "Returns a string representation of this BigDecimal without an exponent field."
println(n4.toPlainString())

// formatted output
val n3output = String.format("%.10f", n3)
println(n3output)        
  • Related