Java中的四舍五入 保留指定位小数

/*
 * 测试四舍五入
 */
package com.icer.test;
 
/**
 *
 * @author Hanbin
 */
public class MyRound {
    public static void main(String[] args) {
        double num = 3.23562;
        double number = 0;
        number = new MyRound().myRound(num,2);
        System.out.println("after:" + number);
    }
 
    private double myRound(double number,int index){
        double result = 0;
        double temp = Math.pow(10, index);
        result = Math.round(number*temp)/temp;
        return result;
    }
}

  因为Java中的round函数在处理完小数之后就去掉了小数位,故先乘100,然后再除以100.0。
保证输出的是小数。否则会被截成整数


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 DecimalFormat 类来实现: ```java float num = 3.1415926f; DecimalFormat decimalFormat = new DecimalFormat("#.000"); String result = decimalFormat.format(num); float roundedNum = Float.parseFloat(result); System.out.println(roundedNum); // 输出 3.142 ``` 其,`"#.000"` 表示保留 3 位小数,并进行四舍五入。将浮点数格式化后得到的字符串,再转换回浮点数即可得到保留 3 位小数四舍五入的结果。 ### 回答2: 在Java,我们可以使用`Math.round()`方法来实现对float类型的数进行四舍五入保留指定位数的小数。 首先,我们需要将float类型的数乘以一个指定的倍数,这样可以将小数位转换为整数位。然后,使用`Math.round()`方法对乘以倍数后的数进行四舍五入。最后,再将得到的结果除以倍数,将整数位转换回小数位。 下面是一个示例代码: ```java public class Main { public static void main(String[] args) { float num = 3.14159f; // 需要进行四舍五入的数 // 将小数位转换为整数位,并进行四舍五入 int temp = Math.round(num * 1000); // 将整数位转换回小数位,并保留3位小数 float result = ((float) temp) / 1000; System.out.println(result); // 输出结果为3.142 } } ``` 在上述代码,我们将需要进行四舍五入的数`num`乘以1000,将小数位移动三位,然后使用`Math.round()`方法对乘以1000后的数进行四舍五入得到`temp`。最后,再将`temp`除以1000,将整数位转换回小数位,得到保留三位小数的结果`result`。 需要注意的是,由于浮点数的精度问题,在进行浮点数的四舍五入操作时可能会出现一些误差。如果要保证精确的四舍五入,建议使用`BigDecimal`类进行计算。 ### 回答3: 在Java对float类型数据进行四舍五入保留3位小数可以使用DecimalFormat类。 首先导入DecimalFormat类: import java.text.DecimalFormat; 然后创建一个DecimalFormat对象,并设置保留3位小数的格式: DecimalFormat df = new DecimalFormat("#.###"); 接下来,我们可以使用format方法将float类型数据按照指定的格式进行四舍五入保留3位小数: float num = 12.3456f; String result = df.format(num); 最后,使用System.out.println输出结果: System.out.println(result); 运行代码,结果将会是12.346。 这是因为DecimalFormat会根据给定的格式对数值进行四舍五入。在本例,使用"#"表示保留数字,而"###"表示保留3位小数。如果想要保留更多或更少的小数位数,只需要修改格式即可。注意,此处的保留小数位数是对结果进行四舍五入,而不是对传入的float类型数据本身进行四舍五入。 这样,我们就实现了对float类型数据进行四舍五入保留3位小数的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值