1. 程式人生 > >數字操作類

數字操作類

static 內置 針對 font 數學函數 數學計算 5.5 tony stat

  數字操作類是針對數字進行處理,可以使用內置數學類,完成。也可以生產隨機數

Math類

  java.lang.Math類是整個的JDK裏面唯一一個與數學計算有關的程序類。著裏面提供有一些基礎的數學函數,這個類中的所有方法都使用了static進行定義,所有的方法都可以通過類名稱直接調用,而此類中有一個round需要特別註意

    四舍五入方法定義:public static long round(double a)

範例:觀察round()方法

1 package cn.Tony.demo;
2 
3 public class TestDemo {
4     public
static void main(String[] args) throws Exception { 5 double num=151516.56515; 6 System.out.println(Math.round(num)); 7 } 8 }

  如果直接使用round方法處理的話默認的處理原則就是將小數位直接進位,

範例:繼續觀察round的數據

 1 package cn.Tony.demo;
 2 
 3 public class TestDemo {
 4     public static void main(String[] args) throws
Exception { 5 System.out.println(Math.round(15.51));//16 6 System.out.println(Math.round(15.5));//16 7 //如果負數小數沒大於0.5都不進位 8 System.out.println(Math.round(-15.5));//-15 9 System.out.println(Math.round(-15.51));//-16 10 } 11 }

  我希望可以準確的保存小數位處理

 1 package
cn.Tony.demo; 2 3 class MyMath{ 4 /** 5 * 進行數據的四舍五入操作 6 * @param num 表示原始操作數據 7 * @param scale 表示保留的小數位數 8 * @return 已經正確四舍五入後的內容 9 */ 10 public static double round(double num,int scale) { 11 return Math.round(num*Math.pow(10, scale))/Math.pow(10, scale); 12 } 13 } 14 public class TestDemo { 15 public static void main(String[] args) throws Exception { 16 System.out.println(MyMath.round(1823.2567,2)); 17 } 18 }

  這種四舍五入的操作是最簡單的處理模式。以後的開發一定會是使用到

隨機類:Random

  在很多語言裏面都支持隨機數子的產生,那麽在Java裏面使用java.util.Random類來實現這種隨機數的處理;

範例:產生隨機數

 1 package cn.Tony.demo;
 2 
 3 import java.util.Random;
 4 
 5 public class TestDemo {
 6     public static void main(String[] args) throws Exception {
 7         Random rand=new Random();
 8         for(int x=0;x<10;x++) {    //100表示最大值,數據的範圍是0到99
 9             System.out.println(rand.nextInt(100)+".");
10         }
11     }
12 }

  在許多的網站上的英文隨機驗證碼實際上就可以通過此類模式完成,

 1 package cn.Tony.demo;
 2 
 3 import java.util.Random;
 4 public class TestDemo {
 5     public static void main(String[] args) throws Exception {
 6         char data[]=new char[] {‘a‘,‘b‘,‘c‘,‘d‘};
 7         Random rand=new Random();
 8         for(int x=0;x<3;x++) {    
 9             System.out.println(data[rand.nextInt(data.length)]+".");
10         }
11     }
12 }

  如果是中文驗證碼也很簡單,寫一個中文驗證碼庫。

數字操作類