java 在 Android 中使用 DecimalFormat 格式化数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27786326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format a number using DecimalFormat in Android
提问by Ralph
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." (1 digit followed by a period) is permitted.
请注意,“0”。(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. For example, some scenarios:
在edittext焦点丢失时,我想阅读edittext中的文本并将其格式化以显示分组的数字并删除不重要的数字。比如一些场景:
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.(在末尾有句点,后面没有数字),我想在编辑文本中显示 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:
所以我在下面执行,假设文本是要格式化的数字:
// 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?
如何摆脱这个?
回答by CJBS
Cast the text
variable to a number first (including handling any exceptions from the parse failing). A long or a double is expected for the single parameter format overload. See: http://developer.android.com/reference/java/text/DecimalFormat.html#inhmethods
text
首先将变量转换为数字(包括处理解析失败的任何异常)。单参数格式重载需要 long 或 double。请参阅: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." doesn't cast directly to a long (e.g. append an extra zero to the end of the string before the cast).
您可能需要添加一些额外的字符串逻辑,以确保在“0”时强制转换有效。不会直接转换为 long(例如,在转换之前在字符串末尾附加一个额外的零)。