英文:
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";
英文:
I have a double. double foo = 123456789.1234;. I want to turn foo into a String. String str = foo+"";. But now foo is equal to "1.234567891234E8". Is there a way I can turn foo into a String without scientific notation?
I've tried
String str = String.format("%.0f", foo);
But that just removes the decimals. It sets str to "123456789";
I've tried
String str = (new BigDecimal(foo))+"";
But that loses accuracy. Its sets str to "123456789.1234000027179718017578125";
答案1
得分: 2
使用%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);
// 如果你想去掉末尾的零
str = new BigDecimal(str).stripTrailingZeros().toString();
System.out.println(str);
}
}
输出:
123456789.123400
123456789.1234
英文:
Use just %f instead of %.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);
}
}
Output:
123456789.123400
123456789.1234
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论