数字格式化
DecimalFormat
是NumberFormat
的一个子类,用于格式化十进制数字。将一些数字格式化为整数、浮点数、科学计数法,百分数等。可以为要输出的数字加上单位或控制数字的精度。
可以在DecimalFormat对象时传递数字格式:
/**
* 使用实例化对象时设置格式化模式
* @param pattern
* @param value
*/
static public void SingleFormat(String pattern, double value){
//实例化DecimalFormat对象
DecimalFormat myFormat = new DecimalFormat(pattern);
String outputString = myFormat.format(value);
System.out.println(value+"|"+pattern+"|"+outputString);
}
也可以通过DecimalFormat
的applyPattern()方法来实现数字格式化:
/**
* 使用applyPattern()方法对数字进行格式化
* @param pattern
* @param value
*/
static public void UseApplyPatternMethodFormat(String pattern, double value){
DecimalFormat myFormat = new DecimalFormat();
myFormat.applyPattern(pattern);
System.out.println(value+"|"+pattern+"|"+myFormat.format(value));
}
使用例子如下:
SingleFormat("###,###.###", 123456.789);//逗号分隔数字
SingleFormat("00000000.###kg", 123456.789);//在数字后加上单位
SingleFormat("000000.00", 123.45);//不存在的以显示
UseApplyPatternMethodFormat("#.###%", 0.456);//将数字转换为百分数形式
UseApplyPatternMethodFormat("###.##", 123456.789);//将小数点后格式为两位
UseApplyPatternMethodFormat("0.00\u2030", 0.456);//将数字格式化为千分数形式
控制台输出结果如下:
123456.789|###,###.###|123,456.789
123456.789|00000000.###kg|00123456.789kg
123.45|000000.00|000123.45
0.456|#.###%|45.6%
123456.789|###.##|123456.79
0.456|0.00‰|456.00‰
格式化模板中的特殊字符及其所代表的含义如下:
字 符 | 字符含义 |
0 | “0”表示以为阿拉伯数字,如果该位不存在数字,则显示0 |
# | “0”表示以为阿拉伯数字,如果该位存在数字,则显示字符,如果该位不存在数字,则不显示 |
- | 符号 |
, | 分组分隔符 |
E | 分隔科学计数法中的尾数和指数 |
% | 放置在数字的前缀or后缀,将数字乘以100显示为百分数 |
\u2030 | 放置在数字的前缀or后缀,将数字乘以1000显示为千分数 |
\u00A4 | 放置在数字的前缀or后缀,作为货币记号 |
‘ | 单引号,当上述特殊字符出现在数字中时,应为特殊符号添加单引号,系统会将此符号视为普通符号处理 |
Math类
Math
类提供了众多数学函数方法,还提供了一些数学常量:
Math.PI//圆周率
Math.E//E
角度和弧度的互换方法:
System.out.println(Math.toDegrees(Math.PI / 2));//取π/2的角度
System.out.println(Math.toRadians(90.0));//取90.0的弧度值取整函数
取整函数:
System.out.println("使用ceil()方法取整:"+Math.ceil(1.2));//ceil()返回大于or等于参数的最小整数
System.out.println("使用floor()方法取整:"+Math.floor(1.2));//floor()返回小于or等于参数的最大整数
System.out.println("使用rint()方法取整:"+Math.rint(1.2));//rint()返回与参数最接近的整数
System.out.println("使用rint()方法取整:"+Math.rint(1.8));
System.out.println("使用round()方法取整:"+Math.round(1.4));//round()将参数加上0.5后返回与参数最近的整数
System.out.println("使用round()方法取整:"+Math.round(1.5f));
控制台输出的结果如下:
使用ceil()方法取整:2.0
使用floor()方法取整:1.0
使用rint()方法取整:1.0
使用rint()方法取整:2.0
使用round()方法取整:1
使用round()方法取整:2
最大值函数 Math.max()
,最小值函数Math.min()
,绝对值函数Math.abs()
.
随机数
Math.random()方法
Math.random()方法默认生成大于等于0.0小于1.0的double型随机数,即0<=Math.random()<1.0。
/**
* 获取char1,char2之间的随机字符
* @param char1
* @param char2
* @return
*/
public static char GetRandomChar(char char1, char char2) {
return(char)(char1+Math.random()*(char2 - char1 + 1));
}
Random类
使用Random类时,Java编译器以系统当前时间作为随机数生成的种子。
Random r = new Random();
System.out.println("随机生成一个整数:"+r.nextInt());
System.out.println("随机生成一个大于等于0小于5的整数:"+r.nextInt(5));