格式化两位小数或双倍 Java 的货币
Formatting two decimal places or currency of double Java
我想弄清楚如何将输出格式化为金钱。由于我是 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);
}
}
好吧,有很多方法可以做到这一点,您可以使用 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...
double amount =500.0;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
System.out.println(currencyFormatter.format(amount));
无论您要使用哪种货币,您都应该使用正确的语言环境
我想弄清楚如何将输出格式化为金钱。由于我是 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);
}
}
好吧,有很多方法可以做到这一点,您可以使用 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...
double amount =500.0;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
System.out.println(currencyFormatter.format(amount));
无论您要使用哪种货币,您都应该使用正确的语言环境