108

I have a Double variable that is 0.0449999 and I would like to round it to 1 decimal place 0.1 .

I am using Kotlin but the Java solution is also helpful.

val number:Double = 0.0449999

I tried getting 1 decimal place with these two solutions:

  1. val solution = Math.round(number * 10.0) / 10.0
  2. val solution = String.format("%.1f", number)

The problem is that I get 0.0 in both cases because it rounds the number from 0.04 to 0.0. It doesn't take all decimals and round it.

I would like to obtain 0.1: 0.045 -> 0.05 -> 0.1

11
  • 66
    Why would you expect 0.0449999 to round to 0.1? That is mathematically incorrect. Feb 27, 2018 at 15:11
  • 11
    Well, that's a pretty meaningless way to round. But, if that's how you want to do it, do it like that: Round to 3 digits, then 2 digits, then 1 digit. Feb 27, 2018 at 15:18
  • 2
    Then start at 4, 5, 6, 7 whatever number of digits. It's still not rounding as the vast majority of people would understand it. Feb 27, 2018 at 15:22
  • 26
    There is no better solution, since this is not a correct way to round numbers. By your logic, I can round $44444.99 to $100000. This is not how rounding works in actuality. Feb 27, 2018 at 15:25
  • 13
    You're looking for a Ceiling and not a Round Oct 2, 2018 at 22:10

13 Answers 13

151

Finally I did what Andy Turner suggested, rounded to 3 decimals, then to 2 and then to 1:

Answer 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()

Answer 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

Result:

0.045 → 0.05 → 0.1

Note: I know it is not how it should work but sometimes you need to round up taking into account all decimals for some special cases so maybe someone finds this useful.

3
  • 18
    One important note to the "Answer 1" it caused my application to crash when i changed language to arabic . the .toDouble() crashed because the number was formatted in arabic (something like this ١٦.٣٤٥٣)
    – A.Alqadomi
    Mar 13, 2019 at 7:30
  • 1 is risky with localisation
    – paul_f
    Jun 6, 2022 at 16:41
  • You can probably save 1000s of crashes here if you update to add DecimalFormatSymbols(Locale.ENGLISH)
    – paul_f
    Jun 6, 2022 at 16:50
74

I know some of the above solutions work perfectly but I want to add another solution that uses ceil and floor concept, which I think is optimized for all the cases.

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

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

here, 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 the 2 digits after decimal use below code.

here, 1.45678 = 1.45

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

Here a list of all available flags: CEILING, DOWN, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP, UNNECESSARY, UP

The detailed information is given in docs

7
  • what is the import for DecimalFormat? I can't find it Mar 21, 2019 at 5:16
  • 1
    I have used below import to execute the above methods, hope it helps. 1) import java.math.BigDecimal 2) import java.math.RoundingMode 3) import java.text.DecimalFormat Mar 22, 2019 at 5:43
  • 2
    I am getting a crash using this. It can cause an issue where to number is formatted as "4,93". Crash: Fatal Exception: java.lang.NumberFormatException For input string: "5,79"
    – paul_f
    Jun 11, 2019 at 14:47
  • 8
    Using this example, beware of locale! I found e.g. portugies which ends up with Fatal Exception: java.lang.NumberFormatException For input string: "0,1" . In order to prevent this issue use DecimalFormat("#.#", DecimalFormatSymbols(Locale.ENGLISH))
    – kotoMJ
    Apr 4, 2020 at 19:37
  • 1
    Do not use. Exception will happen! Aug 20, 2021 at 16:46
61

The BigDecimal rounding features several RoundingModes, including those rounding up (away from zero) or towards positive infinity. If that's what you need, you can perform rounding by calling setScale as follows:

val number = 0.0449999
val rounded = number.toBigDecimal().setScale(1, RoundingMode.UP).toDouble()
println(rounded) // 0.1

Note, however, that it works in a way that will also round anything between 0.0 and 0.1 to 0.1 (e.g. 0.000010.1).

The .toBigDecimal() extension is available since Kotlin 1.2.

0
30

1. Method (using Noelia's idea):

You can pass the number of desired decimal places in a string template and make the precision variable this way:

fun Number.roundTo(
  numFractionDigits: Int
) = "%.${numFractionDigits}f".format(this, Locale.ENGLISH).toDouble()

2. Method (numeric, no string conversion)

fun Double.roundTo(numFractionDigits: Int): Double {
  val factor = 10.0.pow(numFractionDigits.toDouble())
  return (this * factor).roundToInt() / factor
}

One could create an overload for Float as well.

0
27

An example of extension functions for Float and Double, round to n decimal positions.

fun Float.roundTo(n : Int) : Float {
    return "%.${n}f".format(this).toFloat()
}

fun Double.roundTo(n : Int) : Double {
    return "%.${n}f".format(this).toDouble()
}
1
  • 11
    Using this example, beware of locale! I found e.g. portugies which ends up with Fatal Exception: java.lang.NumberFormatException For input string: "0,1" . In order to prevent this issue use "%.${n}f".format(Locale.ENGLISH,this).toFloat()
    – kotoMJ
    Apr 4, 2020 at 19:32
14

In Kotlin I just use this function:

fun roundTheNumber(numInDouble: Double): String {

        return "%.2f".format(numInDouble)

    }
13

Always beware of Locale!

With unspecified locale you can get occasional issue (e.g. with Portugies locale) such as

Fatal Exception: java.lang.NumberFormatException
For input string: "0,1"

1. Solution using DecimalFormat approach

fun Float.roundToOneDecimalPlace(): Float {
    val df = DecimalFormat("#.#", DecimalFormatSymbols(Locale.ENGLISH)).apply {
        roundingMode = RoundingMode.HALF_UP
    }
    return df.format(this).toFloat()
}

2. Solution using string format approach

fun Float.roundTo(decimalPlaces: Int): Float {
    return "%.${decimalPlaces}f".format(Locale.ENGLISH,this).toFloat()
}
2
  • Why not use Locale.getDefault? Oct 9, 2022 at 14:49
  • 1
    @JimOvejera because in formatting you expect a dot in the format. You can be sure English has the dot. But for default locale, when user has for example Portugies locale you get coma in the number so the formatting will fail.
    – kotoMJ
    Oct 10, 2022 at 15:09
3

Try this, its work for me

     val number = 0.045
     var filterUserPrice: String? = "%.2f".format(number)
     Log.v("afterRoundoff"," : $filterUserPrice")// its print filterUserPrice is 0.05
1

For new comers

Using String.format for decimal precision can lead to problems for different languages.

Use the following code to convert Double to as many decimal places as you want.

val price = 6.675668

//to convert to 2 decimal places
totalTime = Math.round(totalTime * 100.0) / 100.00
// totalTime = 6.68

//to convert to 4 decimal places
totalTime = Math.round(totalTime * 10000.0) / 10000.00
// totalTime = 6.6757
0

Try this way for two decimal value return as string

private fun getValue(doubleValue: Double): String {
    return String.format(Locale.US, "%.2f", doubleValue)
}
0

Use Kotlin Extension Function and then call where you need.

fun Double.roundTo(): Double = this.times(100.0).roundToInt() / 100.0
fun Long.roundTo(): Double = this.times(100.0).roundToInt() / 100.0
fun Float.roundTo(): Double = this.times(100.0).roundToInt() / 100.0

Example:

val amount = 156.26588
val roundAmount = amount.roundTo()
Log.d("Amount:" "$roundAmount") // Amount:156.26
0

If You want pure Kotlin solution then you can use roundToInt() method of Kolin

val result = ((number * 1000).roundToInt())/1000.0
-1

Use this extension function:

toBigDecimal(MathContext(3, RoundingMode.HALF_EVEN)).toPlainString()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.