Home > Software design >  Calculation in Kotlin with Double data type gives unexpected result
Calculation in Kotlin with Double data type gives unexpected result

Time:12-16

The calculation below should result in "3.52" but outputs "3.5199999999999996". How can I fix this?

("4.52".toDouble() - 1).toString()

CodePudding user response:

You can also use roundToInt() method to achieve the result as follows

val random = 4.52.toDouble() - 1
val roundoff = (random * 100.0).roundToInt() / 100.0
println(roundoff) //3.52
 

CodePudding user response:

You can use String.format() function like

String.format(Locale.US,"%.2f","4.52".toDouble() - 1)

The .2f means this argument should be formatted as a float and with a precision of 2 digits after the Decimal.

  • Related