Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NumberFormat

I'm trying to use java's NumberFormat class and the getPercentInstance method in a program to calculate tax. What I want the program to display is a percentage with two decimal places. Now, when I tried to format a decimal as a percent before, Java displayed something like 0.0625 as 6%. How do I make Java display a decimal like that or say 0.0625 as "6.25%"?

Code Fragment:

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print("Enter the quantity of items to be purchased: ");
quantity = scan.nextInt();

System.out.print("Enter the unit price: ");
unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;
final double TAX_RATE = .0625;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;

System.out.println("Subtotal: " + fmt1.format(subtotal));
System.out.println("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE));
System.out.println("Total: " + fmt1.format(totalCost));
like image 339
ST33L Avatar asked Jan 28 '26 07:01

ST33L


1 Answers

You can set the minimum number of fraction digits on a NumberFormat instance using setMinimumFractionDigits(int).

For instance:

NumberFormat f = NumberFormat.getPercentInstance();
f.setMinimumFractionDigits(3);
System.out.println(f.format(0.045317d));

Produces:

4.532%

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!