Java数字处理类
此处主要记录使用DecimalFormat格式化浮点数的方法
在Java中,默认格式化形式是:
- 如果数字大于0.001同时小于10000000,则使用常规小数表示
- 如果不在这个范围内是用科学计数法
使用DecimalFormat可以格式化浮点数
1. 常见用法
1.1 控制小数位数
1 | import java.text.DecimalFormat; |
1.2 千位分隔符
1 | DecimalFormat df = new DecimalFormat("#,###.00"); |
#,###.00:#表示可选位,,表示千位分隔符- 若不足两位小数,自动补 0
1.3 前导零
1 | DecimalFormat df = new DecimalFormat("00000.00"); |
00000.00:整数部分至少 5 位,不足补 0,小数部分固定 2 位
1.4 百分比
1 | DecimalFormat df = new DecimalFormat("#.##%"); |
#%:自动 ×100,并加%
1.5 自定义前后缀
1 | DecimalFormat df = new DecimalFormat("¥#,###.00元"); |
- 前后缀(如
¥、元)会直接加在格式化结果中
1.6 解析字符串为数字
1 | import java.text.DecimalFormat; |
parse()方法能将格式化字符串转换回Number
2. DecimalFormat vs String.format() vs BigDecimal
| 方法 | 适用场景 | 示例 |
|---|---|---|
DecimalFormat |
复杂格式(前导零、千分位、前后缀) | new DecimalFormat("#,###.00").format(1234567.89) |
String.format() |
简单格式(小数点、千分位) | String.format("%,.2f", 1234567.89) |
BigDecimal |
高精度计算(金融/科学计算) | new BigDecimal("1234.56789").setScale(2, RoundingMode.HALF_UP) |
通过特殊方法
1 | DecimalFormat ft = new DecimalFormat(); |
数学运算Math类
Math类可以实现很多数学运算
常量
- Math.PI \(pai\)
- Math.E
常用数学方法:
- double sin(double a)
- var cos
- tan
- asin
- acos
- atan
- toRadians() //将角度转换为弧度
- toDegrees() // 将弧度转化为角度
- exp() //e的几次方
- pow(double a, double b): 取a的b次方
- sqrt
- cbrt //立方根
- log(double a) // lna
- log10(double a)
都是传入double返回double,所以精度不准确
取整函数用法:
- ceil(double a) : 向上取整
- floor
- rint(double): 返回和参数最近的整数,如果距离一样则取得偶数
最大值最小值绝对值
和cpp一样也重载了
- max
- min
- abs
随机数
1 | Math.Random() |
- 默认生产的是 0 - 1 之间的任何double数字,但是稍加处理就可以变成产生任意范围的数字:
1
m + (int)(Math.Random() * n) // 返回[m, m + n)之间的数字
除了Math的Random类,Java有一个Random专门来返回随机数字:
Random类有以下常见用法:
- nextInt() 返回随机整数
- nextInt(int n) 返回[0, n)的数字
- nextLong
- nextdouble
大数字运算BigInteger
构造函数:1
2
3
4public BigInteger(String val) {}
// 调用构造函数:
BigInteger a = new BigInteger("123")
注意\” \” 不可以省略
封装的方法:
public BigInteger add(BigInteger val) // +,下列省略所有参数
- subtract(BI val) // -
- multiply(Bi val) // *
- divide(Bi val) // 除法
- remainder(Bi val) // 取余
- pow(int exponent) // 对它取exponent次方
- negate() : 取相反数
- shiftLeft(int n): 将数字左移n位,如果n是负数做右移操作
- shiftRight(int n)
- and()
- or()
- compareTo() // 大于返回1, 小于返回-1
- equals() 比较
- min() 最小值
- max()取最大值
j 7
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 梦始!
评论
