简体   繁体   English

使用Android中的DecimalFormat格式化数字

[英]Format a number using DecimalFormat in Android

I have an EditText and I have set an input filter to only allow numbers which complains this regular expression: 我有一个EditText,我设置了一个输入过滤器,只允许抱怨这个正则表达式的数字:

^\\d{1,8}(\\.\\d{0,2})?$

that is, 8 integer and 2 fractional digits. 也就是说,8个整数和2个小数位数。

Note that, "0." 注意,“0” (1 digit followed by a period) is permitted. (允许1位数后跟一段时间)。

On edittext focus lost, I would like to read the text in the edittext and format it to show numbers grouped and removing not significant digits. 在edittext焦点丢失时,我想阅读edittext中的文本并对其进行格式化以显示分组的数字并删除无效数字。 For example, some scenarios: 例如,某些场景:

1) if user types 1000. (with period at the end and not followed by digits), I want to display 1,000 in edittext 2) if user types 000012. or 000012 or 000012.0 or 000012.00 I want to show 12 3) If user types 1230.90 I want to display 1,230.9 1)如果用户输入1000.(结尾处有句号,而不是数字),我想在edittext中显示1,000 2)如果用户输入000012.或000012或000012.0或000012.00我要显示12 3)如果用户类型1230.90我想显示1,230.9

so I perform below, let's say text is the number to be formatted: 所以我在下面执行,假设text是要格式化的数字:

                    // Prepare format to apply
                    DecimalFormat format = new DecimalFormat();
                    format.setGroupingUsed(true);
                    format.setMaximumIntegerDigits(8);
                    format.setMaximumFractionDigits(2);

                    // Formats the number
                    String formattedText = format.format(text);

I know I can do: 我知道我能做到:

DecimalFormat format = new DecimalFormat("########.##");

so when applying format using: 因此在使用格式时:

String formattedText = format.format(text);

It crashes. 它崩溃了。

For example I have tried to format 0. and 0.5 numbers with no luck. 例如,我试图格式化0.和0.5数字,没有运气。

How to get rid of this? 如何摆脱这个?

Cast the text variable to a number first (including handling any exceptions from the parse failing). 首先将text变量转换为数字(包括处理解析失败的任何异常)。 A long or a double is expected for the single parameter format overload. 单参数格式过载需要长或双。 See: http://developer.android.com/reference/java/text/DecimalFormat.html#inhmethods 请参阅: http//developer.android.com/reference/java/text/DecimalFormat.html#inhmethods

You might need to add some extra string logic to ensure that the cast works if "0." 您可能需要添加一些额外的字符串逻辑,以确保在“0”时转换可以工作。 doesn't cast directly to a long (eg append an extra zero to the end of the string before the cast). 不会直接转换为long(例如,在转换之前将额外的零附加到字符串的末尾)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM