java 中四舍五入保留一位小数

本文通过一个Java程序示例介绍了如何使用DecimalFormat类来格式化浮点数,具体展示了将一个浮点数除以1000并保留一位小数的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Test {


public static void main(String[] args) {
double d = 1671.0;
DecimalFormat df = new DecimalFormat("#.0");
System.out.println(df.format(d / 1000));


}


}

//输出结果为:1.7

Java中,四舍五入保留2小数可以使用多种方法,其中最常用的方法是使用`Math.round()`函数或`BigDecimal`类。以下是两种常见的方法: ### 方法一:使用`Math.round()` ```java public class RoundExample { public static void main(String[] args) { double num = 3.14159; double rounded = Math.round(num * 100.0) / 100.0; System.out.println("四舍五入后的结果是: " + rounded); } } ``` 在这个例子中,`num * 100.0`将数字放大100倍,然后使用`Math.round()`进行四舍五入,最后再除以100.0得到保留2小数的值。 ### 方法二:使用`BigDecimal` ```java import java.math.BigDecimal; import java.math.RoundingMode; public class RoundExample { public static void main(String[] args) { double num = 3.14159; BigDecimal bd = new BigDecimal(num); bd = bd.setScale(2, RoundingMode.HALF_UP); double rounded = bd.doubleValue(); System.out.println("四舍五入后的结果是: " + rounded); } } ``` 在这个例子中,`BigDecimal`类提供了更精确的控制,`setScale(2, RoundingMode.HALF_UP)`方法将数字四舍五入到2小数,`RoundingMode.HALF_UP`表示四舍五入的方式。 ### 方法三:使用`String.format()` ```java public class RoundExample { public static void main(String[] args) { double num = 3.14159; String formatted = String.format("%.2f", num); double rounded = Double.parseDouble(formatted); System.out.println("四舍五入后的结果是: " + rounded); } } ``` 在这个例子中,`String.format("%.2f", num)`将数字格式化为保留2小数的字符串,然后使用`Double.parseDouble()`将其转换回`double`类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值