Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Percentage to show decimals

Tags:

java

I wrote a program today and I need to show percentage in my output but if I have an input of .05375 I need it to display as 5.375% I thought I could do that by using a NumberFormat but my final display is simply 5%. Is there a a way to make it show the decimals? Or how would I code around this? The program functions properly it's just that one output that needs to be formatted differently. Below is what I have for my output for that line of code right now.

    System.out.println("Interest Rate:  " + percent.format(InterestRate));
like image 221
Jeremy B Avatar asked Feb 08 '12 08:02

Jeremy B


3 Answers

You can do that using NumberFormat in Java. Below is the sample code:

NumberFormat numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(3);

System.out.println("Interest Rate:  " + numberFormat.format(InterestRate));

A better approach is to use NumberFormat with Locale, as below:

NumberFormat numberFormat = NumberFormat.getNumberInstance(someLocale);
like image 151
bchetty Avatar answered Oct 19 '22 14:10

bchetty


How about

System.out.printf("Interest Rate:  %.3f%%%n", 100 * InterestRate);
like image 30
Peter Lawrey Avatar answered Oct 19 '22 16:10

Peter Lawrey


If you use the % format, the number is multiplied by 100 for you:

new DecimalFormat("%#0.000").format(rate);
like image 6
Bohemian Avatar answered Oct 19 '22 14:10

Bohemian