我有一个字符串salePrice
,它可以有类似的值29.90000,91.01000
,我想得到像29.90,91.01
小数点后两位数一样的输出。我正在使用一个字符串。
问问题
12626 次
6 回答
15
可能的解决方案之一
new BigDecimal("29.90000").setScale(2).toString()
或者如果你需要四舍五入
new BigDecimal("29.90100").setScale(2, RoundingMode.HALF_UP).toString()
使用 BigDecimal 因为从 String 转换为 double 会丢失精度!
选择适合您情况的舍入模式。
于 2013-06-07T12:45:59.540 回答
8
尝试这个...
DecimalFormat df2 = new DecimalFormat( "#,###,###,###.##" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
于 2013-06-07T12:45:31.900 回答
6
int lastIndex = salePrice.indexOf(".") + 2
salePrice = salePrice.substring(0, lastIndex);
于 2013-06-07T12:45:25.997 回答
2
您可以使用
String.format("%.2f", value);
于 2013-06-07T12:47:16.647 回答
1
您可以使用Apache Commons 数学库
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
ComplexFormat cf = new ComplexFormat(nf);
Complex complex = cf.parse("29.90000");
于 2013-06-07T13:21:43.217 回答
0
Here is an old-school way that matches your question (you always want 2 decimal places)
public class LearnTrim
{
public static void main(final String[] arguments)
{
String value1 = "908.0100";
String value2 = "876.1";
String value3 = "101";
String value4 = "75.75";
String value5 = "31.";
System.out.println(value1 + " => " + trimmy(value1));
System.out.println(value2 + " => " + trimmy(value2));
System.out.println(value3 + " => " + trimmy(value3));
System.out.println(value4 + " => " + trimmy(value4));
System.out.println(value5 + " => " + trimmy(value5));
}
private static String trimmy(final String value)
{
int decimalIndex;
String returnValue;
int valueLength = value.length(); // use StringUtils.length() for null safety.
decimalIndex = value.indexOf('.');
if (decimalIndex != -1)
{
if (decimalIndex < (valueLength - 3))
{
returnValue = value.substring(0, valueLength - 2);
}
else if (decimalIndex == (valueLength - 3))
{
returnValue = value;
}
else if (decimalIndex == (valueLength - 2))
{
returnValue = value + "0";
}
else // decimalIndex == valueLength - 1
{
returnValue = value + "00";
}
}
else
{
returnValue = value + ".00";
}
return returnValue;
}
}
于 2013-06-07T14:29:47.227 回答