您的位置:首页 > 编程语言 > Java开发

11. JAVA常用类库 Part 3 (Math类、Random类、NumberFormat类、BigInteger类和BigDecimal类) ----- 学习笔记

2014-07-15 15:56 731 查看
11.6 Math类
Math类是数学操作类,提供了一些列的数学操作方法,包括求绝对值、三角函数等等,在Math类中提供的一切方法都是静态方法,所以直接由类名名称调用即可,下面简单介绍Math类的基本操作。

JDK关于Math类的描述请戳这里!!!

<pre class="java" name="code">/*
* Math类的基本操作
*/
package org.forfan06.mathdemo;
public class MathDemo01{
public static void main(String args[]){
//Math类中的方法都是静态方法,可以直接使用“类名称.方法名称()”的形式调用即可
System.out.println("求平方根:" + Math.sqrt(9.0));         //输出:3.0
System.out.println("求最大值:" + Math.max(27, 16));       //输出:27
System.out.println("求最小值:" + Math.min(31, 67));       //输出:31
System.out.println("求绝对值:" + Math.abs(-57));          //输出:57
System.out.println("2的3次方:" + Math.pow(2, 3));         //输出:8.0
System.out.println("四舍五入:" + Math.round(25.7));        //输出:26
System.out.println("四舍五入:" + Math.round(25.4));        //输出:25
System.out.println("四舍五入:" + Math.round(25.5));        //输出:26
System.out.println("随机数0-1:" + Math.random());
System.out.println("随机数0-100:" + Math.random() * 100);
}
}




11.7 Random类

Random类是随机数产生类,可以指定一个随机数的范围,然后任意产生在此范围中的数字。Random类中的常用方法如下:

================================================================================

public boolean nextBoolean()                        //随机生成boolean值
public double nextDouble()                       //随机生成double值
public float nexFloat()                        //随机生成float值
public int nextInt()                        //随机生成int值
public int nextInt(int n)                        //随机生成给定最大值的int值
public long nextLong()                           //随机生成long值

================================================================================

范例:生成10个随机数字,且数字不大于100

/*
* 生成10个随机数字,且每个数字不大于100
*/
//package org.forfan06.random;
import java.util.Random;
public class RandomDemo01{
public static void main(String args[]){
Random rd = new Random();
for (int i = 0; i < 10; i++){
System.out.print(rd.nextInt(100) + "\t");
}
}
}


11.8 NumberFormat类

11.8.1 NumberFormat类的基本使用

NumberFormat表示数字的格式化类,即可以按照本地的风格习惯进行数字的显示。此类的定义如下:

public abstract class NumberFormat extends Format


NumberFormat类是一个抽象类,和DateFormat、MessageFormat类一样,都是Format类的子类。NumberFormat类在使用时可以使用NumberFormat类中提供的静态方法为其实例化。其常用方法如下:

===========================================================================================================

public static Locale[] getAvailableLocales()                            //返回所有语言环境的数组
public static final NumberFormat getInstance()                //返回当前默认语言环境的数字格式
public static NumberFormat getInstance(Locale inLocale)                 //返回指定语言环境的数字格式
public static final NumberFormat getCurrencyInstance()                  //返回当前默认环境的货币格式
public static NumberFormat getCurrencyInstance(Locale inLocale)         //返回指定语言环境的货币格式

===========================================================================================================

范例:使用当前语言环境格式化数字:

/*
* 使用当前语言环境格式化数字
*/
package org.forfan06.numberformatdemo;
import java.text.NumberFormat;
public class NumberFormatDemo01{
public static void main(String args[]){
NumberFormat nf = null;
nf = NumberFormat.getInstance();         //得到默认的数字格式显示
System.out.println("" + nf.format(10000000));
System.out.println("" + nf.format(3574.567));
}
}


运行结果:

-------------------------------------------------
10,000,000
3,574.567

-------------------------------------------------


NumberFormat类有两个字类: DecimalFormat(较为常用)、ChoiceFormat

11.8.2 DecimalFormat类

DecimalFormat类是NumberFormat类的子类,也是Format类的一个子类,主要作用是格式化数字。

但是DecimalFormat类在格式化数字时要比直接使用NumberFormat类更加方便,因为可以直接指定按用于自定义的方式进行格式化操作。 与SimpleDateFormat类类似,如果要进行自定义格式化操作,则必须制定格式化操作的模板。 此模板如下所示:

======================================================================================

标记 位置 描述

0 ----------------> 数字 ----------------> 代表阿拉伯数字,每一个0表示一位阿拉伯数字,如果该位不存在则显示0

# ----------------> 数字 ----------------> 代表阿拉伯数字,每一个#表示一位阿拉伯数字,如果该位不存在则不显示

. ----------------> 数字 ----------------> 小数点分隔符或货币的小数分隔符

- ----------------> 数字 ----------------> 代表负号

, ----------------> 数字 ----------------> 分组分隔符

E ----------------> 数字 ----------------> 分隔科学计数法中的尾数和指数

; ----------------> 子模式边界 ----------------> 分隔正数和负数子模式

% ----------------> 前缀或后缀 ----------------> 数字乘以100并显示百分数

\u2030 ----------------> 前缀或后缀 ----------------> 乘以1000并显示千分比

¤ (\u00A4) ----------------> 前缀或后缀 ----------------> 货币记号,由货币号替换。如果两个同时出现,则用国际货币符号替换; 如果出现在某个模式中,则使用货币小数分隔符,而不是用小数分隔符

' ----------------> 前缀或后缀 ----------------> 用于在前缀或后缀中为特殊字符加引号,例如“#'#”将123格式化为 “#123”。要创建单引号本身,则连续使用两个单引号,例如“o''clock”。

======================================================================================

DecimalFormat类有三个构造方法,如下: 请戳DecimalFormat构造方法

public DecimalFormat()                    //creates a DecimalFormat using the default pattern and symbols for the default locale
public DecimalFormat(String pattern)  //creates a DecimalFormat using the given pattern and the symbols for the default locale
public DecimalFormat(String pattern, DecimalFormatSymbols symbols) //creates a DecimalFormat using the given pattern and symbols


范例:格式化数字

/*
* 格式化数字
*/
package org.forfan06.numberformatdemo;
import java.text.DecimalFormat;
class FormatDemo{
public void format1(String pattern, double value){
DecimalFormat df = null;
df = new DecimalFormat(pattern);       //通过构造方法实例化对象
String str = df.format(value);
System.out.println("使用" + pattern + "格式化数字" + value + ":" + str);
}
}
public class DecimalFormatDemo01{
public static void main(String args[]){
FormatDemo fd = new FormatDemo();
fd.format1("###,###.###", 111222.34567);
fd.format1("000,000.000", 111222.34567);
fd.format1("###,###.###¥", 111222.34567);
fd.format1("000,000.000¥", 111222.34567);
fd.format1("##.###%", 0.345678);
fd.format1("00.###%", 0.345678);
fd.format1("###.###\u2030", 0.345678);
}
}


运行结果:

使用###,###.###格式化数字111222.34567:111,222.346
使用000,000.000格式化数字111222.34567:111,222.346
使用###,###.###¥格式化数字111222.34567:111,222.346¥
使用000,000.000¥格式化数字111222.34567:111,222.346¥
使用##.###%格式化数字0.345678:34.568%
使用00.###%格式化数字0.345678:34.568%
使用###.###‰格式化数字0.345678:345.678‰


11.9 BigInteger类

当一个数字非常大时,则肯定无法使用基本数据类型接收;所以,最早碰到大数字时使用String类进行接收,然后再采用拆分的方式进行计算,但是操作非常麻烦。

java为了解决大数字的问题提供了BigInteger类。 BigInteger类表示是大整数类,定义在java.math包中,如果在操作时一个整型数据已经超过了整数的最大类型长度long,数据无法装入,此时可以使用BigInteger类进行操作。

在BigInteger类中封装了各个常用的基本运算,如下所示:

============================================================================

public BigInteger(String val)                   //将一个字符串变为BigInteger类型的数据
public BigInteger add(BigInteger val)              //加法
public BigInteger subtract(BigInteger val)         //减法
public BigInteger multiply(BigInteger val)         //乘法
public BigInteger divide(BigInteger val)           //除法
public BigInteger max(BigInteger val)              //返回两个大数字中的最大值
public BigInteger min(BigInteger val)              //返回两个大数字中的最小值
public BigInteger[] divideAndRemainder(BigInteger val)       //除法操作,数组的第1个元素为除法的商; 第2个元素为除法的余数。


============================================================================

范例:验证BigInteger类

/*
* 验证Integer类
*/
//package org.forfan06.bigintegerdemo;
import java.math.BigInteger;
public class BigIntegerDemo01{
public static void main(String args[]){
BigInteger b1 = new BigInteger("123456789");
BigInteger b2 = new BigInteger("987654321");

System.out.println("加法操作:" + b2.add(b1));
System.out.println("减法操作:" + b2.subtract(b1));
System.out.println("乘法操作:" + b2.multiply(b1));
System.out.println("除法操作:" + b2.divide(b1));
System.out.println("最大数: " + b2.max(b1));
System.out.println("最小数: " + b2.min(b1));

BigInteger result[] = b2.divideAndRemainder(b1);
System.out.println("商是:" + result[0] + ", 余数是:" + result[1]);
}
}


运行结果:

加法操作:1111111110
减法操作:864197532
乘法操作:121932631112635269
除法操作:8
最大数: 987654321
最小数: 123456789
商是:8, 余数是:9


11.10 BigDecimal类

    对于不需要任何准确计算精度的数字可以直接使用float和double,但是如果需要精确计算的结果,则必须使用BigDecimal类;而且使用BigDecimal类也可以进行大数的操作。

BigDecimal类的常用方法如下:

============================================================================

public BigDecimal(double val)                     //将double表示形式转换为BigDecimal
public BigDecimal(int val)                        //将int表示形式转换为BigDecimal
public BigDecimal(String val)                     //将字符串表示形式转换为BigDecimal
public BigDecimal add(BigInteger augend)          //加、减、乘、除
<pre class="java" name="code">public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor)




============================================================================

范例: 进行四舍五入的四则运算

package org.forfan06.numberdemo;
import java.math.BigDecimal;
/**
* @author HE
* 进行四舍五入的四则运算
*/
class MyMath{
/*class BigDecimal method:
* doubleValue() --> Converts this BigDecimal to a double.
* intValue()  --> Converts this BigDecimal to an int.
* floatValue()  --> Converts this BigDecimal to a float.
* longValue()  --> Converts this BigDecimal to a long.
* shortValueExact()  --> Converts this BigDecimal to a short, checking for lost information.
* byteValueExact() --> Converts this BigDecimal to a byte, checking for lost information.
*/
public static double add(double d1, double d2){    //加法
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.add(b2).doubleValue();
}
public static double sub(double d1, double d2){   //减法
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.subtract(b2).doubleValue();
}
public static double mul(double d1, double d2){   //乘法
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.multiply(b2).doubleValue();
}
public static double div(double d1, double d2, int len){   //除法
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static double round(double d, int len){
BigDecimal b1 = new BigDecimal(d);
BigDecimal b2 = new BigDecimal(1);
//任何一个数字除以1都是原数字
//ROUND_HALF_UP是BigDecimal的一个常量,表示进行四舍五入的操作
/*public static final int ROUND_HALF_UP
*Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant,
*in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5;
*otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.
*/
return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
public class BigDecimalDemo01 {
public static void main(String[] args) {
//因为MyMath类中定义的方法都是静态方法,所以不需要实例化MyMath对象。而直接使用类名调用静态方法
System.out.println("加法运算:" + MyMath.round(MyMath.add(10.345, 3.333), 1));
System.out.println("乘法运算:" + MyMath.round(MyMath.mul(10.345, 3.333), 3));
System.out.println("除法运算:" + MyMath.div(10.345, 3.333, 3));
System.out.println("减法运算:" + MyMath.round(MyMath.sub(10.345, 3.333), 3));
}

}


运行结果:

加法运算: 13.7
乘法运算:34.48
除法运算:3.104
减法运算:7.012
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐