BigInteger & BigDecimal
BigInteger & BigDecimal
1.BigInteger
高精度整数
头文件:
1 | import java.math.BigInteger ; |
1.1类型转换
1.1.1 string
转 BigInteger
1 | Biginteger a = new Biginteger("-114514"); |
1.1.2long
转 BigInteger
1 | // 第一种 |
1.1.3 BigInteger
转String
1 | BigInteger a = new BigInteger("114514"); |
1.2基本运算
1.2.1 add
1 | BigInteger a, b; |
1.2.2 sub
1 | BigInteger a, b; |
1.2.3 mul
1 | BigInteger a, b; |
1.2.4 div(趋0
取整)
1 | BigInteger a, b; |
1.2.4 mod
1 | BigInteger a, b; |
1.2.5 pow
1 | BigInteger a; |
1.2.5 gcd
1 | BigInteger a, b; |
1.2.6 abs
1 | BigInteger a, b; |
1.2.7 neg
取反
1 | BigInteger a, b; |
1.2.9 compareTo
比较大小
相同为0,大正小负。
1 | BigInteger a, b; |
2.BigDecimal
头文件:
1 | import java.math.BigDecimal ; |
2.1类型转换
2.1.1string
转 BigDecimal
1 | BigDecimal a = new BigDecimal("3.141592653589793238462643383279"); |
2.1.2不建议 double
或者 float
转 BigDecimal
比如:
1 | BigDecimal a = new BigDecimal(0.1); |
输出:
1 | 0.1000000000000000055511151231257827021181583404541015625 |
BigDecimalr
转String
1 | BigDecimal a = new BigDecimal("3.141592653589793238462643383279000000000"); |
2.1.3BigDecimalr
转String
并去除末尾0
stripTrailingZeros
1 | BigDecimal a = new BigDecimal("3.141592653589793238462643383279000000000"); |
输出
1 | 3.141592653589793238462643383279 |
2.1.4 四舍五入
- setScale(int, BigDecimal.ROUND_HALF_UP)
1 | BigDecimal a = new BigDecimal("3.141592653589793238462643383279000000000"); |
输出
1 | 3.1416 |
2.2基本运算
2.2.1 add、sub、mul和BigIntager一样
2.2.2div
高精度除法,要设定精度长度:
1 | BigDecimal a = new BigDecimal("2"); |
输出:
1 | 0.666666666666666666666666666667 |
- Title: BigInteger & BigDecimal
- Author: Nannan
- Created at : 2024-03-11 18:37:00
- Updated at : 2024-09-30 20:58:04
- Link: https://redefine.ohevan.com/2024/03/11/四、BigInteger & BigDecimal/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments