您的位置:首页 > 编程语言 > Java开发

JAVA 保留两位小数

2014-04-30 14:25 169 查看
转载自:http://stackoverflow.com/questions/16700928/how-to-round-decimals-to-2-places-after-the-decimal-point-java

Java has a DecimalFormat class for things like this.

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

So you would want to add to your code
DecimalFormat df = new DecimalFormat("###,##0.00");


and change your output to
double totalwotax = (total * tax );
System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
double totalandtax = (total + totalwotax);
System.out.println("The total for your bill with tax is $" + df.format(totalandtax));


This will ensure there are exactly two digits to the right of the decimal point for your cents, and keep at least one to the left in case the total is under a dollar. If its 1,000 or above, it will be formatted with the comma in the right place. Should your
totals be higher than 1 million, you might have to alter it to something like this to get the extra comman
DecimalFormat df = new DecimalFormat("###,###,##0.00");


EDIT: So Java also has built-in support for formatting currency. Forget the DecimalFormatter and use the following:
NumberFormat nf = NumberFormat.getCurrencyInstance();


And then use it just as you would the DecimalFormatter, but without the preceding dollar sign (it will be added by the formatter)
System.out.println("The total for your bill with tax is " + nf.format(totalandtax));


Additionally, this method is locale-sensitive, so if you're in the US it will use dollars, if in Japan it uses yen, and so on.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: