在没有科学记数法的情况下格式化字符串中的双精度数
Formatting A Double In A String Without Scientific Notation
我有一个双。 double foo = 123456789.1234;
。我想把 foo
变成一个字符串。 String str = foo+"";
。但是现在 foo
等于“1.234567891234E8”。有没有一种方法可以将 foo
转换为不带科学记数法的字符串?
我试过了
String str = String.format("%.0f", foo);
但这只是去掉了小数。它将 str
设置为“123456789”;
我试过了
String str = (new BigDecimal(foo))+"";
但这会失去准确性。它设置 str
为“123456789.1234000027179718017578125”;
仅使用 %f
而不是 %.0f
。
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double foo = 123456789.1234;
String str = String.format("%f", foo);
System.out.println(str);
// If you want to get rid of the trailing zeros
str = new BigDecimal(str).stripTrailingZeros().toString();
System.out.println(str);
}
}
输出:
123456789.123400
123456789.1234
我有一个双。 double foo = 123456789.1234;
。我想把 foo
变成一个字符串。 String str = foo+"";
。但是现在 foo
等于“1.234567891234E8”。有没有一种方法可以将 foo
转换为不带科学记数法的字符串?
我试过了
String str = String.format("%.0f", foo);
但这只是去掉了小数。它将 str
设置为“123456789”;
我试过了
String str = (new BigDecimal(foo))+"";
但这会失去准确性。它设置 str
为“123456789.1234000027179718017578125”;
仅使用 %f
而不是 %.0f
。
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double foo = 123456789.1234;
String str = String.format("%f", foo);
System.out.println(str);
// If you want to get rid of the trailing zeros
str = new BigDecimal(str).stripTrailingZeros().toString();
System.out.println(str);
}
}
输出:
123456789.123400
123456789.1234