Setting the Precision of Kotlin Decimal (SPKD)

I try to set the decimal precision of the float, double or decimal data types, and I standardize all coding procedures to the double data type.

I have a decimal number, here, of 0.0449999, and I want to round it up to 0.1, just one digit after the decimal point.

I've tried two ways, the first is using a code like this:

val number: Double = 0.0449999 
val solution = Math.round(number * 10.0 ) / 10.0

Or the second one is using this method:

val number: Double = 0.0449999 
val solution = String.format( "%.1f" , number).toDouble()

But there is a problem, the result is 0.0 not 0.1. I want 0.045 to be 0.05 then 0.1 like that. Any other suggestions?


Solution

Finally I did what my friend suggested by rounding to 3 decimals, then to 2, then to 1:

Method 1

val number:Double = 0.0449999 
val number3digits:Double = String.format( "%.3f" , number).toDouble()
 val number2digits:Double = String.format( "%.2f" , number3digits).toDouble()
 val solution :Double = String.format( "%.1f" , number2digits).toDouble()

Method 2
 
val number:Double = 0.0449999 
val number3digits:Double = Math.round(number * 1000.0 ) / 1000.0 
val number2digits:Double = Math.round(number3digits * 100.0 ) / 100.0 
val solution:Double = Math.round(number2digits * 10.0 ) / 10.0

The result


0.045 → 0.05 → 0.1

Alternative

I know some solutions with perfect performance but I would like to add another solution that uses the concept of functionality, which is optimized for many cases.

Library needs

import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat

For a result like this 1.45678 = 1.46


fun  roundOffDecimal (number: Double): Double? {
     val df = DecimalFormat( "#.##" )
    df.roundingMode = RoundingMode.CEILING
    return df.format(number).toDouble()
}

If you want the lowest value of 2 digits after the decimal use the code below.

1.45678 = 1.45

fun  roundOffDecimal (number: Double): Double? {
     val df = DecimalFormat( "#.##" )
    df.roundingMode = RoundingMode.FLOOR
    return df.format(number).toDouble()
}

Here is a list of available signs you can try: CEILING, DOWN, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP, UNNECESSARY, UP.


Post a Comment

Previous Next

نموذج الاتصال