我有以下问题:我在字符串中存储了很大的值,并且我只能显示7位数长度的数字。这是从字符串转换为浮点型后的例子-我有String300,它应该是300.0,但它是300.0,所有大于7位的东西都应该用科学记数法写(700000000应该是7E+8)它也可以是7.0E8,但我更喜欢7E+8。
我尝试过格式化字符串,但是当我无法在不摆脱科学记数法的情况下摆脱.0时。这有可能吗?
发布于 2016-09-09 01:45:22
java.text包中的类DecimalFormat几乎毫不费力地处理了这一点。针对您的特定案例,稍加一点业务逻辑就可以完成交易。
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class NumberFormatter
{
public static void main(String args[])
{
String stringInput = "1234.5678";
String outputString = null;
if (stringInput.length() < 8)
{
outputString = stringInput;
}
else
{
outputString = scientificOutput(stringInput);
}
System.out.println(outputString);
}
private String scientificOutput(String input)
{
NumberFormat formatter = new DecimalFormat("0.###E0");
Double d = Double.parseDouble(input);
if (d % 1 == 0)
{
// is int
return formatter.format(d.intValue());
}
else
{
// is a double
return formatter.format(d);
}
}
}发布于 2016-09-09 03:13:51
试试这个:
String inputValue = "700000000";
String result;
DecimalFormat df1 = new DecimalFormat("@######");
df1.setMinimumFractionDigits(0);
DecimalFormat df2 = new DecimalFormat("@#####E0");
df2.setMinimumFractionDigits(1);
if (inputValue.length() <= 7) {
result = df1.format(Double.parseDouble(inputValue));
} else {
result = df2.format(Double.parseDouble(inputValue));
}https://stackoverflow.com/questions/39396680
复制相似问题