数字操作类是针对数字进行处理,可以使用内置数学类,完成。也可以生产随机数
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 }
这种四舍五入的操作是最简单的处理模式。以后的开发一定会是使用到
在很多语言里面都支持随机数子的产生,那么在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 }
如果是中文验证码也很简单,写一个中文验证码库。
原文:https://www.cnblogs.com/Tony98/p/10497024.html