【问题标题】:Formatting two decimal places or currency of double Java格式化双Java的两位小数或货币
【发布时间】:2015-01-22 04:47:04
【问题描述】:

我想弄清楚如何将输出格式化为货币。由于我是 Java 的初学者,尽管我愿意接受所有建议,但我想要最简单的解决方案。

public static void main(String[] args) 
 {
    int numUnits;
    double price;
    String item;
    Scanner scan = new Scanner(System.in);

    // get the data
    System.out.println("How many units?");
    numUnits = scan.nextInt();

    System.out.println("What is the price?");
    price = scan.nextDouble();

    scan.nextLine();
    System.out.println("What is the name of the item?");
    item = scan.nextLine();

    //calculations
    double totalCost = numUnits * price;

    System.out.println(numUnits + " units of "+ item + " were purchased for $"+
    price + " each for a total cost of $" + totalCost);

   }

 }

【问题讨论】:

标签: java format double decimal currency


【解决方案1】:

您可以通过多种方式进行操作,您可以使用NumberFormat.getCurrencyInstance(),这将允许您根据当前的语言环境属性格式化值...

System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + NumberFormat.getCurrencyInstance().format(totalCost));

您还可以通过首先获取对实例的引用来格式化 NumberFormat 以满足您的需要...

NumberFormat nf = NumberFormat.getCurrencyInstance();
// Customise format properties...

【讨论】:

    【解决方案2】:
        double amount =500.0;
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
        System.out.println(currencyFormatter.format(amount));
    

    您应该使用适当的语言环境来处理您要使用的任何货币

    【讨论】:

      猜你喜欢
      • 2014-08-18
      • 2020-10-25
      • 1970-01-01
      • 2017-08-15
      • 2011-08-29
      • 2015-10-08
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多