[Java]对double变量进行四舍五入,并保留小数点后位数
2024-08-29 23:01:42
1.功能
将double类型变量进行四舍五入,并保留小数点后位数
2.代码
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat; public class Test { /**
* 保留两位小数,四舍五入
* @param d
* @return
*/
public static double formatDouble1(double d) {
return (double)Math.round(d*100)/100;
} /**
*
* @param d
* @return
*/
public static double formatDouble2(double d) {// 如果不需要四舍五入,可以使用RoundingMode.DOWN
BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP); return bg.doubleValue();
} /**
* 该方法会用逗号将三位数字分开
*
* @param d
* @return
*/
public static String formatDouble3(double d) {
NumberFormat nf = NumberFormat.getNumberInstance(); // 保留两位小数
nf.setMaximumFractionDigits(2); // 如果不需要四舍五入,可以使用RoundingMode.DOWN
nf.setRoundingMode(RoundingMode.UP); return nf.format(d);
} /**
* 简单方法。
*
* @param d
* @return
*/
public static String formatDouble4(double d) {
DecimalFormat df = new DecimalFormat("#.00"); return df.format(d);
} /**
* 如果只是用于程序中的格式化数值然后输出,那么这个方法还是挺方便的。
* 应该是这样使用:System.out.println(String.format("%.2f", d));
* @param d
* @return
*/
public static String formatDouble5(double d) {
return String.format("%.2f", d);
} public static void main(String[] args) {
double d = 1245123.67890; System.out.println(formatDouble1(d));
System.out.println(formatDouble2(d));
System.out.println(formatDouble3(d));
System.out.println(formatDouble4(d));
System.out.println(formatDouble5(d));
} }
3.输出结果:
最新文章
- table隔行变色
- SQLite剖析之动态内存分配
- Android获取TextView显示的字符串宽度
- Java POI Word 写文档
- IOS第六天(1:scrollView 属性和查看大图)
- PAT乙级 1020. 月饼 (25)(只得到23分)
- 《JS高程》JS-Object对象整理
- android ping网络是否成功
- Cocos2dx 截屏
- 深入理解JavaScript中的this关键字
- STL,ATL,WTL之间的联系和区别
- Spring mvc中@RequestMapping 6个基本用法整理
- HDU - 4944 FSF’s game
- html中的table在android端显示
- CentOS 网络设置修改
- iOS真机调试配置
- arm-none-eabi-gcc编译报错:exit.c:(.text.exit+0x16): undefined reference to `_exit'
- 兼容ie10及以上css3加载进度动画
- 昂达 v891 v1 终于 删除 windows 分区 并且恢复了容量。
- 对象内存空间 在创建对象后 运行时 会把对象的方法放到jvm的方法区中 调用时 将方法拿到栈中 执行完后 这个方法会出栈 然后新的方法方法进栈