android - 格式化 Double 并将其放在不带逗号的 TextView 中(如果需要)
android - Format Double and put it in TextView without comma (if needed)
我在 Double
中从服务器获取 "price" 值,我需要将它放在我的应用程序的 TextView 中。问题是:当价格 = 500 时,我得到 500.0,因为它是 Double
。我希望它看起来像 500.55 或 500.50 或只是 500 - 如何以正确的方式格式化这些数字?
谢谢
使用 String#format 方法。
在这里阅读:https://www.dotnetperls.com/format-java
或者在 JavaDoc
您需要像这样使用方法 intValue() 显式获取 int 值:
双d = 5.25;
整数 i = d.intValue();
或
双 d = 5.25;
int i = (int) d;
double price = 500.0;
DecimalFormat format = new DecimalFormat("0.###");
System.out.println(format.format(price));
编辑
好的,不如试试不同的东西:
public static String formatPrice ( double price){
if (price == (long) price)
return String.format("%d", (long) price);
else
return String.format("%s", price);
}
您可以使用 rexgex
进行格式化
1.) 创建一个函数来识别以下条件
如果精度值只包含零则截断它们
若小数点后有非零值则return原值
public String formatValue(double d){
String dStr = String.valueOf(d);
String value = dStr.matches("\d+\.\d*[1-9]\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));
return value;
}
\d+\.\d*[1-9]\d*
:匹配一个或多个数字然后 .
\d*[1-9]\d*
: 匹配一个非零值
测试用例
yourTextView.setText(formatValue(500.00000000)); // 500
yourTextView.setText(formatValue(500.0001)); // 500.0001
yourTextView.setText(formatValue(500)); // 500
yourTextView.setText(formatValue(500.1111)); // 500.1111
我在 Double
中从服务器获取 "price" 值,我需要将它放在我的应用程序的 TextView 中。问题是:当价格 = 500 时,我得到 500.0,因为它是 Double
。我希望它看起来像 500.55 或 500.50 或只是 500 - 如何以正确的方式格式化这些数字?
谢谢
使用 String#format 方法。
在这里阅读:https://www.dotnetperls.com/format-java 或者在 JavaDoc
您需要像这样使用方法 intValue() 显式获取 int 值:
双d = 5.25; 整数 i = d.intValue();
或 双 d = 5.25; int i = (int) d;
double price = 500.0;
DecimalFormat format = new DecimalFormat("0.###");
System.out.println(format.format(price));
编辑
好的,不如试试不同的东西:
public static String formatPrice ( double price){
if (price == (long) price)
return String.format("%d", (long) price);
else
return String.format("%s", price);
}
您可以使用 rexgex
进行格式化
1.) 创建一个函数来识别以下条件
如果精度值只包含零则截断它们
若小数点后有非零值则return原值
public String formatValue(double d){ String dStr = String.valueOf(d); String value = dStr.matches("\d+\.\d*[1-9]\d*") ? dStr : dStr.substring(0,dStr.indexOf(".")); return value; }
\d+\.\d*[1-9]\d*
:匹配一个或多个数字然后 .
\d*[1-9]\d*
: 匹配一个非零值
测试用例
yourTextView.setText(formatValue(500.00000000)); // 500
yourTextView.setText(formatValue(500.0001)); // 500.0001
yourTextView.setText(formatValue(500)); // 500
yourTextView.setText(formatValue(500.1111)); // 500.1111