0

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?

sievy
  • 63
  • 7
  • 1
    Note that this code adds two numbers that are _almost, but not quite_ `0.0000000040` and `0.0000000030`. (`Float` and `Double` are binary floating-point types, and can't store decimal fractions exactly; see [this question](/questions/588004/is-floating-point-math-broken).) To get the exact numbers, start with strings: `"0.0000000040".toBigDecimal()` etc. – gidds Aug 04 '22 at 09:02

2 Answers2

1

Try

println((n1 + n2).toPlainString())
Ivo
  • 18,659
  • 2
  • 23
  • 35
  • The problem is that I need to calculate further with the result and it needs to be the type of BigDecimal not String. – sievy Aug 04 '22 at 07:56
  • 1
    @sievy just continue working with the result of `n1 + n2`. "0.0000000070" is literally the same as "7.0E-9". It's just a different string representation. If you do `println(n1)` you will see it prints "4.0E-9" – Ivo Aug 04 '22 at 08:47
0

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)        
ocos
  • 1,901
  • 1
  • 10
  • 12