Home > Enterprise >  Kotlin - How to eliminate decimals except the first two
Kotlin - How to eliminate decimals except the first two

Time:05-03

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

CodePudding user response:

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

CodePudding user response:

You can set a rounding mode on the DecimalFormat:

DecimalFormat("#.##")
    .apply { roundingMode = RoundingMode.FLOOR }
    .format(3.556)

However, note that a Float does not actually store the number in decimal (base 10), and so it is not a suitable format for a number that you need to have a specific number of decimal places. When you convert it to a String, you may find that the number of decimal places has changed. To ensure a specific number of decimal places, you need BigDecimal.

  • Related