一、Math類
Math類提供了大量的靜態方法來便于我們實現數學計算,如求絕對值、取最大或最小值等。
https://doc.qzxdp.cn/jdk/17/zh/api/java.base/java/lang/Math.html
- 所在模塊:java.base
- 所在包: java.lang
static double abs(double a) 返回a值的絕對值其它重構方法支持不同數據類型:int|long|float|double;
static double max(double a, double b)返回較大者;
static double min(double a, double b)返回較小者;
static double pow(double a, double b)返回a的b次方;
static double sqrt(double a)返回a平方根;
static double log(double a)返回a的對數;
static double sin(double a)返回正弦值;
static double asin(double a)返回反正弦值;
static long round(double a)4舍5入,【注意返回類型】;
static int round(float a)4舍5入,【注意返回類型】;
static double ceil(double a)返回大于a,且最接近a的最小整數;
static double random()[0.0,1)大于或等于 0.0 且小于 1.0的隨機數;
二、BigInteger類
BigInteger用于處理大整數(任意長度的整數) ,位于java.math
。
構造方法
public BigInteger(String val) 將十進制字符串表示形式轉換為 BigInteger。
BigInteger a = new BigInteger("123456789123456789123456789");
常用方法
BigInteger add(BigInteger val)返回值為 (this + val) ;
BigInteger subtract(BigInteger val)返回值為 (this - val) ;
BigInteger multiply(BigInteger val)返回值為 (this * val) ;
BigInteger divide(BigInteger val)返回值為 (this / val) ;
BigInteger remainder(BigInteger val)返回值為 (this % val) ;
BigInteger compareTo(BigInteger val)this大于value -> 1this等于value -> 0this小于value -> -1;
String toString()返回此 BigInteger 的十進制字符串表示形式;
String toString(int radix)返回給定基數中此 BigInteger 的字符串表示形式;
例如:
BigInteger a = new BigInteger("123456789123456789123456789");
BigInteger b = new BigInteger("123456789123456789123456789");
BigInteger c = a.add(b);
System.out.println(a.bitCount());
System.out.println(c);
三、DecimalFormat類
DecimalFormat
位于 java.text.DecimalFormat
是 NumberFormat
(抽象類)的具體子類,用于格式化十進制數。
0:表示一位數字整數:最少是幾位整數,不足時補0小數:最多是幾位小數(4舍5入),不足時補0
#:表示一位數字整數:最少是幾位整數,不補0小數:最多是幾位小數(4舍5入),不補0
,:在數字中用作分組分隔符
.:用于表示小數點的位置。
;:子模式邊界,分隔正數和負數子規則
%:將數字格式化為百分比形式。
例1
0 和 # 的 區別
DecimalFormat decimalFormat = new DecimalFormat("00000");
String rst = decimalFormat.format(123);
System.out.println(rst); // 00123
DecimalFormat decimalFormat = new DecimalFormat("#####");
String rst = decimalFormat.format(123);
System.out.println(rst); // 123
分組分隔符
DecimalFormat decimalFormat = new DecimalFormat(",#####");
String rst = decimalFormat.format(123456);
System.out.println(rst); //
小數點
DecimalFormat decimalFormat = new DecimalFormat(".00"); // 【固定】兩位小數
DecimalFormat decimalFormat = new DecimalFormat(".##"); // 【最多】兩位小數
String rst = decimalFormat.format(3.145926);
System.out.println(rst); //
百分比形式
DecimalFormat decimalFormat = new DecimalFormat("+.00%");
System.out.println(decimalFormat.format(0.6812)); //
子模式邊界(使用;
分隔正負)
DecimalFormat decimalFormat = new DecimalFormat("+.00%;-.00%");
System.out.println(decimalFormat.format(0.6812));
System.out.println(decimalFormat.format(-0.6834));
將字符串轉化為數字
DecimalFormat decimalFormat = new DecimalFormat("¥#.00");
double price = decimalFormat.parse("¥123.45").doubleValue();
System.out.println(price);