Java获取小数点后几位

学习中遇见保留1小数点后位,选择有四种方法:方法:1、用format方法,语法“String.format("%.2f",数值)”;2、用DecimalFormat的format方法;3、用setScale方法进行四舍五入;4、用setMaximumFractionDigits方法。
方法一:String的format方法
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103162408879-655089834.png)
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163239731-963062263.png)
方法二:DecimalFormat的format方法
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163316186-2063136391.png)
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163324958-2107658823.png)
方法三:BigDecimal的setScale方法
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163335596-788806062.png)
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163342585-1342603831.png)
方法四:NumberFormat的setMaximumFractionDigits方法
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163352704-483644913.png)
![](https://img2022.cnblogs.com/blog/2914114/202211/2914114-20221103163359482-2027013002.png)
posted @ 2022-11-03 16:34  wmr123  阅读(207)  评论(0编辑  收藏  举报