一、数字格式化
1、Java主要对浮点型数据进行数字格式化操作,其中浮点型数据包括double型和float型数据,在Java中使用java.text.DecimalFormat格式化数字。
2、在Java中没有格式化的数据遵循一下原则:1)如果数据绝对值大于0.001并且小于10000000,Java将以常规小数形式表示;2)如果绝对值小于0.001或大于10000000,使用科学计数法表示。
3、在Java中可以使用DecimalFormat类进行格式化操作。
4、DecimalFormat是NumberFormat的一个子类,使用格式化十进制数字。可以将数字格式化为整数、浮点数、科学计数法、百分数等。通过使用该类可以为要输出的数字加上单位或控制数字的精度。一般情况下可以在实例化DecimalFormat对象时传递数字格式,也可以通过DecimalFormat类中的applyPattern()方法来实现数字格式化。
5、当格式化数字时,在DecimalFormat类中使用一些特殊字符构成个格式化模板,是数字按照一定的特殊字符规则进行匹配。下图中给出了格式化模板中的特殊字符及其所代表的含义。
示例如下:
import java.text.DecimalFormat;
public class DecimalFormatSimpleDemo {
//使用实例化对象时设置格式化模式
static public void SimpleFormat(String pattern, double value){
//实例化DecimalFormat对象
DecimalFormat myFormat = new DecimalFormat(pattern);
String output = myFormat.format(value);//将数字进行格式化
System.out.println(value + " " + pattern + " " + output);
}
//使用applyPattern()方法对数字进行格式化
static public void UseApplyPatternMethodFormat(String pattern, double value){
DecimalFormat myFormat = new DecimalFormat();//实例化DecimalFormat对象
myFormat.applyPattern(pattern);
System.out.println(value + " " + pattern + " "
+ myFormat.format(value));
}
public static void main(String[] args) {
SimpleFormat("###,###.###", 123456.789);//调用静态SimpleFormat方法
SimpleFormat("00000000.###kg", 123456.789);//在数字后面加上单位
//按照格式模板格式化数字,不存在的位以0显示
SimpleFormat("000000.000", 123.78);
//调用静态UseApplyPatternMethodFormat()方法
UseApplyPatternMethodFormat("#.###%", 0.789);
//将小数点后格式化为两位
UseApplyPatternMethodFormat("###.##", 123456.789);
//将数字转化为千分数形式
UseApplyPatternMethodFormat("0.00\u2030", 0.789);
}
}
输出结果为:
123456.789 ###,###.### 123,456.789
123456.789 00000000.###kg 00123456.789kg
123.78 000000.000 000123.780
0.789 #.###% 78.9%
123456.789 ###.## 123456.79
0.789 0.00‰ 789.00‰
示例解释:
首先使用import关键字将java.text.DecimalFormat这个类包含进来;然后定义两个方法实现格式化虽然这两个方法的参数代表的意义相同,也都可以实现格式化数字的操作,但使用的方式有所不同,SimplFormat()方法是在实例化DecimalFormat对象时设置数字格式化模板,而UseApplyPatternMethodFormat()方法是在实例化DecimalFormat对象后调用applyPattern()方法设置数字格式化模板。
6、在DecimalFormat类中除了可以设置格式化模式来格式化数字之外,还可以使用一些特殊方法对数字进行格式化设置。
示例代码:
import java.text.DecimalFormat;
public class DecimalMethod {
public static void main(String[] args) {
DecimalFormat myFormat = new DecimalFormat();
myFormat.setGroupingSize(2); // 设置将数字分组的大小
String output = myFormat.format(123456.789);
System.out.println("将两个数字分成一组:" + output);
myFormat.setGroupingUsed(false); // 设置是否支持分组
output = myFormat.format(123456.789);
System.out.println("不允许数字分组:" + output);
}
}
运行结果:
将两个数字分成一组:12,34,56.789
不允许数字分组:123456.789
二、数字运算
1、Math类
1)在Math类中提供了众多数学函数方法,主要包括三角函数方法、指数函数方法、取整函数方法、取最大值、最小值及平均值函数方法,这些方法都被定义为static形式。除此之外,Math类还存在一些常用数学常量,如PI、E等。
2)常用数学运算方法
Math类中的常用数学运算方法大致可分为四类,分别为三角函数方法、指数函数方法、取整函数方法及取最大值、最小值和绝对值函数方法。
A)三角函数方法
public static double sin(double a):返回角的三角正弦
public static double cos(double a):返回角的三角余弦
public static double tan(double a):返回角的三角正切
public static double asin(double a):返回一个值的反正弦
public static double acos(double a):返回一个值的反余弦
public static double atan(double a):返回一个值的反正切
public static double toRadians(double angdeg):将角度转换为弧度
public static double toDegrees(double angrad):将弧度转换为角度
注意:角度与弧度的转换通常是不精确的。
示例如下:
public class TrigonometricFunction {
public static void main(String[] args) {
System.out.println("90度的正弦值:" + Math.sin(Math.PI/2));
System.out.println("0度的余弦值:" + Math.cos(0));
System.out.println("60度的正切值:" + Math.tan(Math.PI/3));
System.out.println("2的平方根与2商的反正弦值:"
+ Math.asin(Math.sqrt(2) / 2));
System.out.println("2的平方根与2商的反余弦值:"
+ Math.acos(Math.sqrt(2) / 2));
System.out.println("1的反正切值:" + Math.atan(1));
System.out.println("120度的弧度值:" + Math.toRadians(120.0));
System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI/2));
}
}
运行结果:
90度的正弦值:1.0
0度的余弦值:1.0
60度的正切值:1.7320508075688767
2的平方根与2商的反正弦值:0.7853981633974484
2的平方根与2商的反余弦值:0.7853981633974483
1的反正切值:0.7853981633974483
120度的弧度值:2.0943951023931953
π/2的角度值:90.0
B)指数函数方法
public static double exp(double a):用于获取e的a次方
public static double log(double a):用于取自然对数
public static double log10(double a):用于取底数为10的对数
public static double sqrt(double a):用于取a的平方根,其中a的值不能为负值
public static double cbrt(double a):用于取a的立方根
public static double pow(double a, double b):用于取a的b次方
示例如下:
public class ExponentFunction {
public static void main(String[] args) {
System.out.println("e的平方根:" + Math.exp(2));
System.out.println("以e为底的2的对数:" + Math.log(2));
System.out.println("以10为底的2的对数:" + Math.log10(2));
System.out.println("4的平方根:" + Math.sqrt(4));
System.out.println("8的立方根:" + Math.cbrt(8));
System.out.println("2的2次方值:" + Math.pow(2, 2));
}
}
运行结果:
e的平方根:7.38905609893065
以e为底的2的对数:0.6931471805599453
以10为底的2的对数:0.3010299956639812
4的平方根:2.0
8的立方根:2.0
2的2次方值:4.0
C)取整函数方法
public static double ceil(double a):返回大于等于参数的最小整数
public static double floor(double a):返回小于等于参数的最大整数
public static double rint(double a):返回与参数最接近的整数,如果两个同为整数且铜奖接近,则结果取偶数
public static int round(float a):将参数加上0.5后返回与参数最近的整数
public static long round(double a):将参数加上0.5后返回与参数最近的证书,然后强制转换为长整型
示例如下:
public class IntFunction {
public static void main(String[] args) {
System.out.println("使用cell()方法取整:" + Math.ceil(5.2));
System.out.println("使用floor()方法取整:" + Math.floor(2.5));
System.out.println("使用rint()方法取整:" + Math.rint(2.7));
System.out.println("使用rint()方法取整:" + Math.rint(2.5));
System.out.println("使用round()方法取整:" + Math.round(3.4f));
System.out.println("使用round()方法取整:" + Math.round(2.5));
}
}
运行结果:
使用cell()方法取整:6.0
使用floor()方法取整:2.0
使用rint()方法取整:3.0
使用rint()方法取整:2.0
使用round()方法取整:3
使用round()方法取整:3
D)取最大值、最小值、绝对值函数方法
public static double max(double a, double b):取a与b之间的最大值
public static int min(int a, int b):取a与b之间的最小值,参数为整型
public static long min(long a, long b)
public static float min(float a, float b)
public static double min(double a, double b)
public static int abs(int a):返回整型参数的绝对值
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)
示例如下:
public class AnyFunction {
public static void main(String[] args) {
System.out.println("4和8的较大者:" + Math.max(4, 8));
System.out.println("4.4和4的较小者:" + Math.min(4.4, 4));
System.out.println("-7的绝对值:" + Math.abs(-7));
}
}
运行结果:
4和8的较大者:8
4.4和4的较小者:4.0
-7的绝对值:7
三、随机数
1、在Java中主要提供了两种方式产生随机数,分别为Math类的random()方法和Random类提供的产生各种数据类型的随机数的方法。
2、Math.random()方法
random()方法默认生成大于等于0.0小于1.0的double型随机数。
示例如下:
public class MathRandom {
public static int GetEvenNum(double num1, double num2){
int s = (int)num1 + (int)(Math.random() * (num2 - num1));
if(s % 2 == 0){
return s;
} else {
return s + 1;
}
}
public static void main(String[] args) {
System.out.println("任意一个2~32之间的偶数:" + GetEvenNum(2, 32));
}
}
运行结果:
任意一个2~32之间的偶数:16
使用Math类的random()方法也可以随机生成字符,可以使用如下代码生成a~z之间的字符
(char)('a' + Math.random() * ('z' - 'a' + 1));
注意:random()方法返回的值实际上是伪随机数,它通过复杂的运算而得到一系列的数。该方法是通过当前时间作为随机数生成器的参数,所以每次执行程序都会产生不同的随机数。
3、Random类
1)除random()方法外,Java中还提供了一种可以获取随机数的方式,就是java.util.Random类。可以通过实例化一个Random对象创建一个随机数生成器。
语法:Random r = new Random();
以这种方式实例化对象时,Java编译器以系统当前事件作为随机数生成器的种子,所以产生的随机数将不同,但是如果运行速度太快,也会产生两次运行结果相同的随机数。
同时,也可以实例化Random类对象时,设置随机数生成器的种子。
语法:Random r = new Random(seedValue);
2)在Random类中提供了获取各种数据类型随机数的方法,如下示:
public int nextInt():返回一个随机整数
public int nextInt(int n):返回大于等于0小于n的随机整数
public long nextLont():返回一个随机长整型值
public boolean nextBoolean():返回一个随机布尔型值
public float nextFloat():返回一个随机浮点型值
public double nextDouble():返回一个随机双精度型值
public double nextGaussian():返回一个概率密度为高斯分布的双精度值
示例如下:
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random r = new Random();
System.out.println("随机产生一个整数:" + r.nextInt());
System.out.println("随机产生一个大于等于0小于10的整数:" + r.nextInt(10));
System.out.println("随机产生一个布尔型的值:" + r.nextBoolean());
System.out.println("随机产生一个双精度型的值:" + r.nextDouble());
System.out.println("随机产生一个浮点型的值:" + r.nextFloat());
System.out.println("随机产生一个概率密度为高斯分布的双精度值:" + r.nextGaussian());
}
}
运行结果:
随机产生一个整数:-424981078
随机产生一个大于等于0小于10的整数:4
随机产生一个布尔型的值:false
随机产生一个双精度型的值:0.25240105761711384
随机产生一个浮点型的值:0.23873341
随机产生一个概率密度为高斯分布的双精度值:-1.8056914375790063
四、大数字运算
1、在Java中提供了大数字的操作类,即java.math.BIgInteger类与jaba.math.BIgDecimal类。这两个类用于高精度计算,其中BigInteger类是针对大整数的处理类,而BIgDecimal类则是针对大小数的处理类。
2、BigInteger
1)BigInteger支持任意精度的整数,也就是说在运算中BigInteger类型可以准确地表示任何大小的整数值而不会丢失任何信息。
2)使用BigInteger类,可以实例化一个BigInteger对象,并自动调用相应的构造函数。BigInteger类具有很多构造函数,但最直接的一种方式是参数以字符串形式代表要处理的数字。
语法:public BigInteger(String val)
3)常用的运算方法:
public BigInteger add(BigInteger val):做加法运算
public BigInteger subtract(BigInteger val):做减法运算
public BigInteger multiply(BigInteger val):做乘法运算
public BigInteger divide(BigInteger val):做除法运算
public BigInteger
remainder(BigInteger val):做取余运算
public
BigInteger[] divideAndRemainder(BigInteger val):用数组返回余数和商,结果数组中第一个为商,第二个值为余数
public
BigInteger pow(int exponent):进行取参数的exponent次方操作
public
BigInteger negate():取相反数
public
BigInteger shiftLeft(int n):将数字左移n位,如果n为负数,做右移操作
public
BigInteger shiftRight(int n):将数字右移n位,如果n为负数,做左移操作
public
BigInteger and(BigInteger val):做与操作
public
BigInteger or(BigInteger val):做或操作
public
int compareTo(BigInteger val):做数字比较操作
public
boolean equals(Object x):当参数x是BigInteger类型的数字并且数值相等时,返回true
public
BigInteger min(BigInteger val):返回较小的数值
public
BigInteger max(BigInteger val):返回较大的数值
示例如下:
import
java.math.BigInteger;
public
class BigIntegerDemo {
public
static void main(String[] args) {
BigInteger bigInstance = new BigInteger("4");
System.out.println("加法操作:" + bigInstance.add(new BigInteger("2")));
System.out.println("减法操作:" + bigInstance.subtract(new BigInteger("2")));
System.out.println("乘法操作:" + bigInstance.multiply(new BigInteger("2")));
System.out.println("除法操作:" + bigInstance.divide(new BigInteger("2")));
System.out.println("取商:" + bigInstance.divideAndRemainder(new BigInteger("3"))[0]);
System.out.println("取余数:" + bigInstance.divideAndRemainder(new BigInteger("3"))[1]);
System.out.println("做2次方操作:" + bigInstance.pow(2));
System.out.println("取相反数:" + bigInstance.negate());
}
}
运算结果:
加法操作:6
减法操作:2
乘法操作:8
除法操作:2
取商:1
取余数:1
做2次方操作:16
取相反数:-4
3、BigDecimal
1)BigDecimal和BigInteger都能实现大数字的运算,不同的是BigDecimal加入了小时的概念。其用到了java.math.BigDecimal类。
2)构造方法
public
BigDecimal(double val)
public
BigDecimal(String val)
3)BigDecimal类型的数字可以用来做超大的浮点数运算,但是在所有的运算中除法是最复杂的,因为在除不尽的情况下末尾小数点的处理是需要考虑的。
4)常用方法
public
BigDecimal add(BigDecimal augend):做加法操作
public
BigDecimal subtract(BigDecimal subtrahend):做减法操作
public
BigDecimal multiply(BigDecimal multiplicand):做乘法操作
public
BigDecimal divide(BigDecimal divisor, int scale, int roundingMode):做除法操作,方法中3个参数分别代表除数、上的小数点后的位数、近似处理模式。
近似处理模式如下表所示:
示例如下:
import java.math.BigDecimal;
public class BigDecimalDemo {
static final int location = 10;
public BigDecimal add(double value1, double value2){
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.add(b2);
}
public BigDecimal sub(double value1, double value2){
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.subtract(b2);
}
public BigDecimal mul(double value1, double value2){
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.multiply(b2);
}
public BigDecimal div(double value1, double value2){
return div(value1, value2, location);
}
public BigDecimal div(double value1, double value2, int b){
if(b < 0){
System.out.println("b值必须大于等于0");
}
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.divide(b2, b, BigDecimal.ROUND_HALF_UP);
}
public static void main(String[] args) {
BigDecimalDemo b = new BigDecimalDemo();
System.out.println("加法操作:" + b.add(-7.5, 8.9));
System.out.println("减法操作:" + b.sub(-7.5, 8.9));
System.out.println("乘法操作:" + b.mul(-7.5, 8.9));
System.out.println("除法操作,结果小数后保留10位:" + b.div(10, 2));
System.out.println("出发操作,结果小数后保留5位:" + b.div(-7.5, 8.9, 5));
}
}
运算结果:
加法操作:1.4
减法操作:-16.4
乘法操作:-66.75
除法操作,结果小数后保留10位:5.0000000000
出发操作,结果小数后保留5位:-0.84270