[英]Math.round() not working
我正在用Java開發計算器,但是“。” 按鈕功能不起作用。 如果刪除Math.round()
我有時會得到1.1999999而不是1.2。 我該如何解決這個問題? 我試過在堆棧溢出時查找幾個Math.round()
解決方案,但沒有一個起作用。
x = Math.round(x + (y / (Math.pow(10, z)) * 1000) / (double) 1000);
到目前為止,上面的代碼是我嘗試過的代碼。
您必須在除法之前四舍五入。
double d = x + y / Math.pow(10, z);
double r = Math.round(d * 1e3) / 1e3; // round to 3 decimal places
您可以嘗試使用NumberFormat類設置文本格式
public String formatNumber(int n){
NumberFormat f= NumberFormat.getInstance();
f.setMinimumFractionDigits(2);// minimum digits after comma
f.setMaximumFractionDigits(2);//maximum digits after comma
String formattedN = f.format(n);
return formattedN;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.