将一个双精度浮点数格式化为不使用科学计数法的字符串。

huangapple go评论71阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年10月2日 02:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64161632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定