Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert double into percentage

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, "%")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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%.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading