How can i convert example 1.07 into 7%, 1.50 into 50%, 2.25 into 125% e.t.c.
My code so far and it’s not working:
private static final NumberFormat PERCENTAGE_FORMAT = NumberFormat.getInstance();
PERCENTAGE_FORMAT.setMaximumFractionDigits(0);
PERCENTAGE_FORMAT.format(1.07, "%")
>Solution :
You can do it like this:
double number = 1.15;
int percentage = 0;
if (number - 1 < 1) {
percentage = (int) Math.round(number * 100) % 100;
} else {
percentage = (int) (number * 100);
}
System.out.println(percentage + "%"); // Output: 15%
For numbers smaller than 2 (e.g. 1.07) this will give you the percentage over 100 (i.e. 7%). For bigger numbers it will give you the percentage directly, so 2.35 becomes 235%.