Search code examples
kotlinmathdecimal

Kotlin - How to eliminate decimals except the first two


What I want to achieve is to keep 2 decimals and eliminate any extra decimals without any rounding for example

3.556664 to 3.55 (NOT ROUNDING)

I Tried the following

    "%.2f".format(3.556).toFloat() // the result is 3.56
    DecimalFormat("#.##").format(3.556).toFloat() // the result is 3.56
    BigDecimal(3.556).setScale(2, RoundingMode.DOWN).toFloat() // the result is 3.56

Solution

  • val x = Math.floor(3.556 * 100) / 100 // == 3.55
    

    Math.floor returns value that less than or equal to the argument and is equal to a mathematical integer.

    In our case 3.556 * 100 = 355.6 and the floor would be 355.0, hence 355/100 = 3.55