Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 四舍五入

作者:殘月殺手   发布日期:2025-08-17   浏览:7

public class RoundExample {
    public static void main(String[] args) {
        double number = 12.3456;
        int decimalPlace = 2; // 四舍五入到小数点后两位

        // 使用 Math.round() 方法进行四舍五入
        double roundedNumber = Math.round(number * Math.pow(10, decimalPlace)) / Math.pow(10, decimalPlace);

        System.out.println("原始数字: " + number);
        System.out.println("四舍五入后的数字: " + roundedNumber);
    }
}

解释说明:

  1. double number = 12.3456;: 定义一个需要四舍五入的浮点数。
  2. int decimalPlace = 2;: 指定四舍五入到小数点后几位(这里是两位)。
  3. *`Math.round(number Math.pow(10, decimalPlace)) / Math.pow(10, decimalPlace);`**:
    • number * Math.pow(10, decimalPlace):将数字乘以 10 的指定次方,移动小数点位置。
    • Math.round():对调整后的大数值进行四舍五入。
    • 再除以 Math.pow(10, decimalPlace) 将小数点移回原位。

这个代码段展示了如何使用 Math.round() 方法实现四舍五入的功能。

上一篇:java string转json

下一篇:java stack

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站