Double decimal formatting in Java

后端 未结 14 1240
囚心锁ツ
囚心锁ツ 2020-11-22 05:17

I\'m having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it\'s 4.00 instead?

14条回答
  •  心在旅途
    2020-11-22 05:33

    First import NumberFormat. Then add this:

    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
    

    This will give you two decimal places and put a dollar sign if it's dealing with currency.

    import java.text.NumberFormat;
    public class Payroll 
    {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) 
        {
        int hoursWorked = 80;
        double hourlyPay = 15.52;
    
        double grossPay = hoursWorked * hourlyPay;
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
    
        System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
        }
    
    }
    

提交回复
热议问题