Java實現控制小數精度的方法
random()函數源碼
/** * Creates a new random number generator. This constructor sets * the seed of the random number generator to a value very likely * to be distinct from any other invocation of this constructor. */ public Random() { this(seedUniquifier() ^ System.nanoTime()); }
nextDouble()函數源碼
public double nextDouble() { return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT; }
我們可以這樣生成一個doublel類型隨機數。
代碼
import java.util.Random;public class Format { public static void main(String[] args) { //方法1 Random random=new Random(); double num=random.nextDouble(); //方法2 //double num= Math.random(); System.out.println(num); }}
輸出:
0.04342853133845903
我們發現輸出結果是一個[0,1)之間的很長的小數值。如果我們不需要這么長的小數位數應該怎么處理呢?
控制小數位數1.截斷 多余小數位
public class Format { public static void main(String[] args) { double d = 1.23456789; // 需要幾位小數,就乘以10的幾次方,再強轉。 int i = (int) (d * 100000);//注意等式右邊帶了兩個() // 又轉回去。 double d2 = (double) i / 100000;//等式右邊必須加(double)并且i/10000不要加括號 System.out.println(d2); } }
輸出
1.23456
2.利用數字格式化
import java.text.NumberFormat;public class Format { public static void main(String[] args) { double d = 1.23456789; NumberFormat Nformat = NumberFormat.getInstance(); // 設置小數位數。 Nformat.setMaximumFractionDigits(2); // 對d進行轉換。 String str = Nformat.format(d); // 將String類型轉化位double //方法1 //Double num = Double.parseDouble(str); //方法2 double num=Double.valueOf(str).doubleValue(); System.out.println(num); }}
輸出:
1.23457
3.利用十進制格式化器
import java.text.DecimalFormat;public class Format { public static void main(String[] args) { double d = 1.23456789; // 設置格式樣式 DecimalFormat Dformat=new DecimalFormat('0.00000'); // 格式化 String str=Dformat.format(d); //將String類型轉化位double //Double num = Double.parseDouble(str);//方法1 double num=Double.valueOf(str).doubleValue();//方法2 System.out.println(num); }}
輸出
1.23457
4.利用BigDecimal(終極)
BigDecimal是java.math包中提供的API類,可處理超過16位有效位的數。在開發中,如果我們需要精確計算的結果,則必須使用BigDecimal類來操作。 BigDecimal所創建的是對象,故我們不能使用傳統的+、-、*、/等算術運算符直接對其對象進行數學運算,而必須調用其相對應的方法。方法中的參數也必須是BigDecimal的對象。構造器是類的特殊方法,專門用來創建對象,特別是帶有參數的對象。import java.math.BigDecimal;public class Format { public static void main(String[] args) { double d = 1.23456789; BigDecimal decimal=new BigDecimal(d); // 四舍五入為五位小數 double d2=decimal.setScale(5,BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(d2); }}
輸出:
1.23457
參考資料:Java控制小數位,獲得隨機數BigDecimal詳解Java字符串和數字間的轉換
到此這篇關于Java實現控制小數精度的方法的文章就介紹到這了,更多相關Java 小數精度內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: