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
and change your output to
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
EDIT: So Java also has built-in support for formatting currency. Forget the DecimalFormatter and use the following:
And then use it just as you would the DecimalFormatter, but without the preceding dollar sign (it will be added by the formatter)
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.
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.
相关文章推荐
- Java 向下取整并保留两位小数
- java保留两位小数
- java:double四舍五入并保留两位小数的方法
- Java中double类型保留两位小数
- Java两整数相除保留两位小数
- Java保留两位小数 and 浮点数精确计算 and BigDecimal介绍
- java保留两位小数4种方法
- java保留两位小数4种方法
- java DecimalFormat保留两位小数,四舍五入记录
- Java使用千分位并保留两位小数
- java保留两位小数
- Java float保留两位小数或多位小数
- Java 保留两位小数
- JAVA-保留两位小数的方法
- java保留两位小数4种方法
- java保留两位小数
- java保留两位小数问题
- java使double/float保留两位小数的多方法 java保留两位小数
- Java保留两位小数的几种写法总结
- java保留两位小数4种方法