1. 程式人生 > 其它 >Java Math常用方法

Java Math常用方法

1Math.abs() 絕對值

2 Math.max 最大值

3 Math.min 最小值

4 Math.round() 四捨五入取整

4.1 保留幾位小數

5 Math.addExact() 整數之和

6 Math.cbrt() 立方根

7 Math.sqrt() 平方根

8 Math.ceil() 向上取整

9 Math.floor() 向下取整

10 Math.random() 取隨機數

10.1 隨機數

11 Math.negateExact() 取反數

package haoqipei.demo;

import java.text.DecimalFormat; import java.util.Random; /** * @author :zhouqiang * @date :2021/6/29 15:42 * @description: * @version: $ */ public class math { public static void main(String[] args) { /** 1 * absolute value 絕對值 * 值:1213.123 */ System.out.println(Math.abs(
-1213.123)); /** 2 * 最大值 * 值:2232 */ System.out.println(Math.max(112,2232)); /** 3 * 最小值 * 值:112 */ System.out.println(Math.min(112,2232)); /** 4 * 四捨五入取整 * 值:24 */ System.out.println(Math.round(
23.75433)); /** 4.1 保留小數 * 示例:2位小數 和 4位小數 * 值:23.75 和23.7544 */ DecimalFormat b = new DecimalFormat("0.00"); String format = b.format(23.75433); System.out.println(format); DecimalFormat c = new DecimalFormat("0.0000"); String format1 = c.format(23.75438823); System.out.println(format1); /** 5 * 整數之和 Int 和long型別 * 值:24 */ System.out.println(Math.addExact(-123,-23)); /** 6 * 立方根 * 值:3.0 */ System.out.println(Math.cbrt(27)); /** 7 * 平方根 * 值:4.0 */ System.out.println(Math.sqrt(16)); /** 8 * 向上取整 * 值:11.0 */ System.out.println(Math.ceil(10.1)); /** 9 * 向下取整 * 值:10.0 */ System.out.println(Math.floor(10.9)); /** 10 * 獲取0-1隨機數 或者 Math.random()*(最大值-最小值)+最小值 * 示例 取 10-15 之間的隨機數 * 值:13.653823703277194 */ System.out.println(Math.random()*5+10); /** 10.1 * 獲取0-1隨機數 或者 Math.random()*(最大值-最小值)+最小值 * 示例 取 10-15 之間的隨機數 * 值:13.653823703277194 */ //以系統當前時間作為隨機數生成的種子 Random random=new Random(); //返回一個大於0且小於100的整數 System.out.println(random.nextInt(100)); //返回一個隨機浮點型 System.out.println(random.nextFloat()); //返回一個隨機布林型值 System.out.println(random.nextBoolean()); //返回一個隨機雙精度型 System.out.println(random.nextDouble()); //返回一個隨機長整形 System.out.println(random.nextLong()); /** 11 取反值 * * 值:-123 */ System.out.println(Math.negateExact(123)); } }