Java:以百万为单位的格式数字 [英] Java: Format number in millions

查看:608
本文介绍了Java:以百万为单位的格式数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


1,000,000 => 1.00M使用DecimalFormat(或其他标准格式化程序)来格式化数字

1,234,567 => 1.23M

1,234,567,890 => 1234.57M

blockquote>

基本上将一些数字除以100万,保留2位小数,最后打一个M。我想创建一个NumberFormat的新子类,但它看起来比我想象的更复杂。



我正在编写一个具有格式方法的API,如下所示:

  public String format(double value,Unit unit); //单元是枚举

在内部,我将单元对象映射到NumberFormatters。实现是这样的:

$ p $ public String format(double value,Unit unit)
{
NumberFormatter formatter = formatters.get(unit);
return formatter.format(value);





$ b请注意,因为这个原因,我不能指望客户被除以100万,我不能只是使用String.format()没有包装它在一个NumberFormatter。

解决方案

  String.format(%。2fM,theNumber / 1000000.0); 

欲了解更多信息,请参阅 String.format javadocs


Is there a way to use DecimalFormat (or some other standard formatter) to format numbers like this:

1,000,000 => 1.00M

1,234,567 => 1.23M

1,234,567,890 => 1234.57M

Basically dividing some number by 1 million, keeping 2 decimal places, and slapping an 'M' on the end. I've thought about creating a new subclass of NumberFormat but it looks trickier than I imagined.

I'm writing an API that has a format method that looks like this:

public String format(double value, Unit unit); // Unit is an enum

Internally, I'm mapping Unit objects to NumberFormatters. The implementation is something like this:

public String format(double value, Unit unit)
{
    NumberFormatter formatter = formatters.get(unit);
    return formatter.format(value);
}

Note that because of this, I can't expect the client to divide by 1 million, and I can't just use String.format() without wrapping it in a NumberFormatter.

解决方案

String.format("%.2fM", theNumber/ 1000000.0);

For more information see the String.format javadocs.

这篇关于Java:以百万为单位的格式数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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