1、Math中四舍五入的方法
Math.ceil(double a)向上舍入,將數值向上舍入為最為接近的整數,返回值是double類型
Math.floor(double a)向下舍入,將數值向下舍入為最為接近的整數,返回值是double類型
Math.round(float a)標准舍入,將數值四舍五入為最為接近的整數,返回值是int類型
Math.round(double a)標准舍入,將數值四舍五入為最為接近的整數,返回值是long類型
2、Math中random生成隨機數
Math.random()生成大於等於0,小於1的隨機數
3、Random類生成隨機數
兩種構造方式:第一種使用默認的種子(當前時間作為種子),另一個使用long型整數為種子,Random類可以生成布爾型、浮點類型、整數等類型的隨機數,還可以指定生成隨機數的范圍
4、BigDecimal處理小數
兩種構造方式:第一種直接value寫數字的值,第二種用String
import java.math.BigDecimal;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class TestNumber {
public static void main(String[] args){
//ceil返回大的值
System.out.println(Math.ceil(-10.1)); //-10.0
System.out.println(Math.ceil(10.7)); //11.0
System.out.println(Math.ceil(-0.7)); //-0.0
System.out.println(Math.ceil(0.0)); //0.0
System.out.println(Math.ceil(-0.0)); //-0.0
System.out.println(Math.ceil(-1.7)); //-1.0
//floor返回小的值
System.out.println(Math.floor(-10.1)); //-11.0
System.out.println(Math.floor(10.7)); //10.0
System.out.println(Math.floor(-0.7)); //-1.0
System.out.println(Math.floor(0.0)); //0.0
System.out.println(Math.floor(-0.0)); //-0.0
System.out.println(Math.floor(-1.7)); //-2.0
//round四舍五入,float返回int,double返回long
System.out.println(Math.round(10.5)); //11
System.out.println(Math.round(-10.5)); //-10
//Math生成隨機數
System.out.println(Math.random());
//Random類生成隨機數
Random rand=new Random();
System.out.println(rand.nextBoolean());
System.out.println(rand.nextDouble());
System.out.println(rand.nextInt());
System.out.println(rand.nextInt(10));
//Random使用當前時間作為Random的種子
Random rand2 = new Random(System.currentTimeMillis());
System.out.println(rand2.nextBoolean());
System.out.println(rand2.nextDouble());
System.out.println(rand2.nextInt());
System.out.println(rand2.nextInt(10));
System.out.println(rand2.nextInt(5));
//ThreadLocalRandom
ThreadLocalRandom rand3 = ThreadLocalRandom.current();
System.out.println(rand3.nextInt(5,10));
//BigDecimal
System.out.println(0.8 - 0.7); //0.10000000000000009
BigDecimal a1=new BigDecimal(0.1);
BigDecimal b1=new BigDecimal(0.9);
BigDecimal c1=a1.add(b1);
System.out.println("a1.add(b1)="+c1); //a1.add(b1)=1.0000000000000000277555756156289135105907917022705078125
BigDecimal a2=new BigDecimal("0.1");
BigDecimal b2=new BigDecimal("0.9");
BigDecimal c2=a2.add(b2);
System.out.println("a2="+a2); //a2=0.1
System.out.println("a2.add(b2)="+c2); //a2.add(b2)=1.0
}
}