簡體   English   中英

如何在 java 中設置雙原始類型的特定位數?

[英]How to set particular number of Digits in double primitive type in java?

我想要雙原始類型的特定位數(小數點前+小數點后)。

有沒有辦法做到這一點...

例如:(固定為 6 位數字)

  1. 如果我們有 12.666666667 給出 output 為 12.6667
  2. 如果我們有 5.6666666667 給出 output 為 5.66667
  3. 但是,如果我們有 9.00000000,則 output 只有 9。

為了更清楚地理解,我附上了一張圖片。 在此處輸入圖像描述

有兩件事要考慮。 一個是如果您需要精確的精度,因為浮點運算可能無法滿足您的要求。 有關詳細信息,請參閱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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM