kotlindecimalformattofixed

How to convert toFixed(2) in Kotlin


What should I write in the place of area.toFixed(2)

fun main(args: Array<String>) {
    val a = 20
    val h = 30
    val area = a * h / 2
    println("Triangle area = ${area.toFixed(2)}")
}

Solution

  • I think you really meet a problem that how to convert Javascript code to Kotlin code. You need to ask the question clearly at next time, :). you can use String#format instead, for example:

    println("%.2f".format(1.0))  // print "1.00"
    
    println("%.2f".format(1.253))  // print "1.25"
    
    println("%.2f".format(1.255))  // print "1.26"
    

    AND the area is an Int which means it will truncates the precision, Kotlin doesn't like as Javascript use the numeric by default, so you should let a*h divide by a Double, then your code is like as below:

    //                  v--- use a `Double` instead
    val area = a * h / 2.0
    
    println("Triangle area = ${"%.2f".format(area)}")