简体   繁体   中英

BigDecimal - too many leading zeros in fraction part

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?

Try

println((n1 + n2).toPlainString())

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)        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM