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));
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);
How about
System.out.printf("Interest Rate: %.3f%%%n", 100 * InterestRate);
If you use the %
format, the number is multiplied by 100
for you:
new DecimalFormat("%#0.000").format(rate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With