java小数位的例子
时间:2023-11-30 02:37:12
方式一:
四舍五入
double f = 111231.5585;
四舍五入 保留两位小数,可以用String的format函数,
方法如下:
System.out.println(String.format("%.2f", x1));
System.out.println(String.format("%.2f", x2));
DecimalFormat转换最简便
public void m2() {
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
}
例:new java.text.DecimalFormat(”#.00″).format(3.1415926)
#.00 表示两位小数 #.0000四位小数 以此类推…
方式三:
double d = 3.1415926;
String result = String .format(”%.2f”);
%.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。
方式四:
此外如果使用struts标签做输出的话,有个format属性,设置为format="0.00"就是保留两位小数
例如
<bean:write name="entity" property="dkhAFSumPl" format="0.00" />
JAVA中保留N位小数的方法,例子 .
import java.text.DecimalFormat;
public class numberFarmat {
public static void main(String[] args) {
double sd = 23.2558896635;
//第一种方法 10000.0这个小数点后只表示保留小数,和位数没关系。
double d1 = (double) (Math.round(sd*10000)/10000.0000000000);
double d2 = (double) (Math.round(sd*10000)/10000.0);
System.out.println("4位小数测试:"+d1);
System.out.println("4位小数测试:"+d2);
//第二种方法
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df3 = new DecimalFormat("##.000");
System.out.println("3位小数:"+df3.format(sd));
System.out.println("2位小数:"+df2.format(sd));
}
}
运行结果如下:
4位小数测试:23.2559
4位小数测试:23.2559
3位小数:23.256
2位小数:23.26
标签:java小数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java中Collections.emptyList()的注意事项
2022-02-28 18:04:54
创建Android守护进程实例(底层服务)
2021-11-12 01:37:09
![](https://img.aspxhome.com/file/2023/7/139357_0s.jpg)
springboot项目启动,但是访问报404错误的问题
2022-09-21 10:30:10
![](https://img.aspxhome.com/file/2023/3/61253_0s.jpg)
基于Java+SpringBoot+Vue前后端分离实现仓库管理系统
2023-11-01 04:21:22
![](https://img.aspxhome.com/file/2023/1/99861_0s.jpg)
Spring请求参数校验功能实例演示
2023-04-26 02:05:53
Android 使用flow实现倒计时的方式
2023-04-13 10:36:29
Android进度条ProgressBar的实现代码
2023-01-30 07:12:22
![](https://img.aspxhome.com/file/2023/1/138221_0s.jpg)
C#中隐式运行CMD命令行窗口的方法
2021-06-11 18:47:07
springboot实现通过路径从磁盘直接读取图片
2023-09-01 03:01:01
![](https://img.aspxhome.com/file/2023/9/80949_0s.png)
Java数据结构之链表(动力节点之Java学院整理)
2022-08-29 16:40:18
![](https://img.aspxhome.com/file/2023/9/81929_0s.png)
Thread类interrupt interrupted及isInterrupted区别
2023-07-20 06:52:20
![](https://img.aspxhome.com/file/2023/8/57688_0s.png)
Android O添加桌面快捷方式的示例
2022-12-27 07:53:19
Java保留两位小数的几种写法总结
2022-04-19 06:53:06
Java实现简易界面通讯录
2023-02-09 20:12:59
![](https://img.aspxhome.com/file/2023/2/71912_0s.jpg)
Java图像之自定义角度旋转(实例)
2023-10-07 21:04:28
java实现打砖块游戏算法
2023-01-28 20:51:06
Android使用Matrix旋转图片模拟碟片加载过程
2022-08-22 21:07:32
![](https://img.aspxhome.com/file/2023/4/139624_0s.png)
MAC下如何设置JDK环境变量
2023-12-20 16:05:24
![](https://img.aspxhome.com/file/2023/8/72598_0s.jpg)
完美解决idea moudle没有蓝色的小方块的问题
2021-05-28 16:09:03
![](https://img.aspxhome.com/file/2023/7/68197_0s.jpg)
java 域对象共享数据的实现
2022-04-26 15:22:14
![](https://img.aspxhome.com/file/2023/7/113397_0s.png)