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?
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
}