java字符串转换成四舍五入后的精确度为两位小数的浮点数
时间: 2023-03-29 14:04:14 浏览: 81
可以使用Java中的DecimalFormat类来实现字符串转换成四舍五入后的精确度为两位小数的浮点数。具体代码如下:
```
String str = "3.1415926";
double num = Double.parseDouble(str);
DecimalFormat df = new DecimalFormat("#.00");
String result = df.format(num);
System.out.println(result);
```
输出结果为:3.14
相关问题
java浮点数四舍五入保留一位小数
你可以使用Java中的Math类来进行浮点数的四舍五入保留一位小数。以下是示例代码:
```
double num = 3.1415926;
double roundedNum = Math.round(num * 10.0) / 10.0;
System.out.println(roundedNum);
```
输出结果为:3.1
在这个例子中,我们将浮点数num乘以10,然后使用Math类的round()方法将结果四舍五入为整数。接着,我们将结果除以10.0,以保留一位小数,并将结果存储在变量roundedNum中。最后,我们使用System.out.println()方法来打印roundedNum的值。
Java浮点数四舍五入保留一位小数
你可以使用Java中的Math类来进行浮点数的四舍五入保留一位小数。以下是示例代码:
```
double num = 3.1415926;
double roundedNum = Math.round(num * 10.0) / 10.0;
System.out.println(roundedNum);
```
输出结果为:3.1
在这个例子中,我们将浮点数num乘以10,然后使用Math类的round()方法将结果四舍五入为整数。接着,我们将结果除以10.0,以保留一位小数,并将结果存储在变量roundedNum中。最后,我们使用System.out.println()方法来打印roundedNum的值。