1

I'm trying to make a method that receives a double and returns a String formatted with always 2 numbers after the decimal point.

For example:

1990.999 -> "1990.99"

1990.9 -> "1990.90"

I'm developing an app using Android min sdk version 21, so I can't use DecimalFormat. I manage to make something that works like this:

public String currencyFormat(double value) {
        return value < 0
                ? String.format("-" + currencySymbol + "%.02f", value * -1)
                : String.format(currencySymbol + "%.02f", value);
    }

However, the problem here is that if I try for example 1999,369 the result is "1999,37". Is there a way to prevent the round out?

Jose Gonzalez
  • 1,491
  • 3
  • 25
  • 51

1 Answers1

1

You could use this method instead:

public static String currencyFormat(double value) {
    value = Math.floor(value * 100) / 100; // rounds 'value' to 2 decimal places
    return String.format("%.2f", value); // converts 'value' to string
}
Gooz
  • 1,106
  • 2
  • 9
  • 20