[英]How to format a Double value properly with decimal separator?
I have an application that uses thousands separator (,) and decimal separator (.), I used this app on 2 tablets with the same languages (Español) on their configuration and when I do some process with numbers like 15,000.00 on the first one the answer was correct but in the second tablet the number changes to 15,00. 我有一个使用千位分隔符(,)和十进制分隔符(。)的应用程序,我在2个平板电脑上使用了该应用程序,它们的配置都使用相同的语言(Español),当我在第一个平板电脑上使用数字150.00答案是正确的,但在第二台平板电脑中,该数字更改为15,00。 I changed the language of the second to English, and it works, but how can i set this number format on code?
我将秒的语言更改为英语,并且可以使用,但是如何在代码中设置此数字格式?
Sorry about the errors this is not my native language. 抱歉,这不是我的母语。
Thanks for the help 谢谢您的帮助
You could format a double value in code like this: 您可以使用以下代码来格式化双精度值:
/**
* format a number properly
* @param number
* @return
*/
public String formatDecimal(double number) {
DecimalFormat nf = new DecimalFormat("###.###.###.##0,00");
// or this way: nf = new DecimalFormat("###,###,###,##0.00");
String formatted = nf.format(number);
return formatted;
}
And then set it to a TextView: 然后将其设置为TextView:
mytextview.setText("MyDouble: " + formatDecimal(somedouble));
You could format using 您可以使用格式化
NumberFormat nf = NumberFormat.getInstance(new Locale("es", "MX")); //for example
But beware because depending on the locale, even if is the same language but different country the decimal char and grouping char my change, for example 但要注意,因为取决于语言环境,即使是相同的语言但不同的国家/地区,小数字符和分组字符也可以更改,例如
NumberFormat nf = NumberFormat.getInstance(new Locale("es", "CO")); //displays 15.000,00
You can get an instance for a specific locale as specified by the android docs : 您可以获取android docs指定的特定语言环境的实例:
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
However, you should not change the locale when displaying stuff to the user imho. 但是,向用户imho显示内容时,请勿更改语言环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.