[英]How to set particular number of Digits in double primitive type in java?
我想要雙原始類型的特定位數(小數點前+小數點后)。
有沒有辦法做到這一點...
例如:(固定為 6 位數字)
為了更清楚地理解,我附上了一張圖片。 在此處輸入圖像描述
有兩件事要考慮。 一個是如果您需要精確的精度,因為浮點運算可能無法滿足您的要求。 有關詳細信息,請參閱BigDecimal
class。 另一個是你想要做的:顯示一個帶有一定小數位數的數字。 您可以使用String.format
完成此操作。 例如
double num = 5.666666666;
String formatted = String.format("%.5f", num);
和
System.out.println(formatted)
將 output
5.66667
import java.text.DecimalFormat;
public class rounding {
public static void main(String[] args) {
double num = 23.122345899;
double rounded = Math.round(num * 1000000) / 1000000.0;
System.out.println(rounded);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.