使用DecimalFormat格式化数字 [英] Formatting numbers using DecimalFormat

查看:76
本文介绍了使用DecimalFormat格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DecimalFormat格式化价格,但这不适用于所有版本.

I am trying to format prices using DecimalFormat, but this isn't working for all variations.

DecimalFormat df = new DecimalFormat("0.##")
df.format(7.8)
df.format(85.0)

打印

7.80

85

但是"7.79999"的格式设置为"7.8",而不是"7.80".我尝试过用这种方式做事

but "7.79999" gets formatted as "7.8", not "7.80". I have tried doing things this way

DecimalFormat df = new DecimalFormat("0.00")

强制两个dp,但是"85.0"的格式设置为"85.00"而不是"85"!

to force two dp, but then "85.0" gets formatted as "85.00" not "85"!

是否可以捕获所有变化,以便将价格打印为#,##或#.##?例如:

Is there a way of capturing all variations, so that prices are printed either as #, ##, or #.##? For example:

5,55,5.55,5.50,500,500.40

5, 55, 5.55, 5.50, 500, 500.40

推荐答案

似乎没有一个单独的 formatter 可以解决.我建议您使用"0.00" 格式,并将.00" 替换为空字符串.

This doesn't seem to be solved by a single formatter. I suggest you use "0.00" format and replace ".00" with an empty string.

public static String myFormat(double number) {
  DecimalFormat df = new DecimalFormat("0.00");
  return df.format(number).replaceAll("\\.00$", "");
}

这篇关于使用DecimalFormat格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆