[英]rounding double to 2 decimal places
i need to output e4 and e5 to 2 decimal places as it is currency 我需要将e4和e5输出到2个小数位,因为它是货币
public void afterTextChanged(Editable s) {
if (e2.getText().toString() != "")
{
double salePrice = Double.parseDouble(e2.getText().toString());
double ebayFee = salePrice / 10.00;
double paypalFee = (salePrice * 0.034) + 0.2;
double roundedPPFee = Math.round(paypalFee*100.00)/100.00;
double roundedEbayFee = Math.round(ebayFee*100.00)/100.00;
e4.setText(String.valueOf(roundedEbayFee));
e5.setText(String.valueOf(roundedPPFee));
}
}
You can use DecimalFormat (possibly with RoundingMode ) 您可以使用DecimalFormat (可能与RoundingMode一起使用 )
//double yourNumber = ...;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);
String roundedValue = df.format(yourNumber);
or BigDecimal : 或BigDecimal :
//double yourNumber = ...;
String roundedValue = BigDecimal.valueOf(yourNumber).setScale(2, BigDecimal.ROUND_FLOOR).toString();
You may want to take a look at the other thread where similar question was answered quite extensively. 您可能想看看另一个线程 ,其中相当广泛地回答了类似问题。
On a side note, you probably should not store money in a double because of their inability to represent decimal values accurately - see this question for broader explanation. 附带说明,您可能不应该将钱存成两倍,因为它们无法准确表示十进制值-有关更多说明,请参见此问题 。
What is the current output you are getting? 您得到的当前输出是多少?
Also try this and check your output. 也可以尝试一下并检查您的输出。 Instead of .00, just add .0
代替.00,只需添加.0
double roundedPPFee = Math.round(paypalFee*100.0)/100.0;
double roundedEbayFee = Math.round(ebayFee*100.0)/100.0;
double ebayFee = salePrice / 10.00;
double paypalFee = (salePrice * 0.034) + 0.2;
double roundedPPFee = Math.round(paypalFee*100.0)/100.0;
double roundedEbayFee = Math.round(ebayFee*100.0)/100.0;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(roundedPPFee));
System.out.println(f.format(roundedEbayFee));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.