java中保留两位小数的方法:1、使用DecimalFormat;2、使用String.format方法。
在Java中保留两位小数可以使用DecimalFormat类或者使用String.format方法。
1、使用DecimalFormat类的示例代码如下:
import java.text.DecimalFormat; public class Main { public static void main(String[] args) { double number = 3.1415926; DecimalFormat decimalFormat = new DecimalFormat("#.##"); String formattedNumber = decimalFormat.format(number); System.out.println("Formatted number: " + formattedNumber); } } 输出结果为:Formatted number: 3.14
2、使用String.format方法的示例代码如下:
public class Main { public static void main(String[] args) { double number = 3.1415926; String formattedNumber = String.format("%.2f", number); System.out.println("Formatted number: " + formattedNumber); } } 输出结果为:Formatted number: 3.14
在上述示例代码中,首先定义了一个double类型的变量number,表示原始的数字。然后通过DecimalFormat类或者String.format方法对该数字进行格式化,使用"%.2f"表示保留两位小数。最后将格式化后的结果打印出来 。
以上就是java中怎么保留两位小数的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号