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.输出结果:

最新文章

  1. table隔行变色
  2. SQLite剖析之动态内存分配
  3. Android获取TextView显示的字符串宽度
  4. Java POI Word 写文档
  5. IOS第六天(1:scrollView 属性和查看大图)
  6. PAT乙级 1020. 月饼 (25)(只得到23分)
  7. 《JS高程》JS-Object对象整理
  8. android ping网络是否成功
  9. Cocos2dx 截屏
  10. 深入理解JavaScript中的this关键字
  11. STL,ATL,WTL之间的联系和区别
  12. Spring mvc中@RequestMapping 6个基本用法整理
  13. HDU - 4944 FSF’s game
  14. html中的table在android端显示
  15. CentOS 网络设置修改
  16. iOS真机调试配置
  17. arm-none-eabi-gcc编译报错:exit.c:(.text.exit+0x16): undefined reference to `_exit'
  18. 兼容ie10及以上css3加载进度动画
  19. 昂达 v891 v1 终于 删除 windows 分区 并且恢复了容量。
  20. 对象内存空间 在创建对象后 运行时 会把对象的方法放到jvm的方法区中 调用时 将方法拿到栈中 执行完后 这个方法会出栈 然后新的方法方法进栈

热门文章

  1. sed命令入门
  2. OFDM Modulation Scheme
  3. Java类的加载过程与ClassLoader的理解及测试
  4. VFP调用API来控制USB摄像头,实现拍照或录像
  5. zabbix-proxy配置文件参数说明
  6. CDN&对象存储
  7. Android进程永生技术终极揭秘:进程被杀底层原理、APP应对技巧
  8. 陶陶摘苹果(升级版)P1478_巧妙模拟
  9. 《自拍教程19》aapt_apk信息查看工具
  10. Git分支的管理