如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串 [英] How to nicely format floating numbers to string without unnecessary decimal 0's

查看:25
本文介绍了如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个 64 位的 double 可以精确地表示整数 +/- 253.

鉴于这个事实,我选择使用 double 类型作为我所有类型的单一类型,因为我的最大整数是一个无符号的 32 位数字.

但现在我必须打印这些伪整数,但问题是它们也与实际的双精度混合在一起.

那么如何在 Java 中很好地打印这些双打?

我已经尝试过 String.format("%f", value),它很接近,只是我得到了很多小值的尾随零.

这是 %f

的示例输出<前>232.000000000.180000000001237875192.04.58000000000.000000001.23450000

我想要的是:

<前>2320.1812378751924.5801.2345

当然,我可以编写一个函数来修剪这些零,但是由于字符串操作,性能损失很大.我可以用其他格式的代码做得更好吗?


Tom E. 和 Jeremy S. 的答案是不可接受的,因为他们都任意四舍五入到小数点后两位.回答前请先了解问题.


请注意 String.format(format, args...)locale-dependent(见下面的答案).

解决方案

如果想法是打印作为双精度数存储的整数,就好像它们是整数一样,否则打印双精度数:

public static String fmt(double d){if(d == (long) d)return String.format("%d",(long)d);别的return String.format("%s",d);}

产生:

2320.1812378751924.5801.2345

并且不依赖字符串操作.

A 64-bit double can represent integer +/- 253 exactly.

Given this fact, I choose to use a double type as a single type for all my types, since my largest integer is an unsigned 32-bit number.

But now I have to print these pseudo integers, but the problem is they are also mixed in with actual doubles.

So how do I print these doubles nicely in Java?

I have tried String.format("%f", value), which is close, except I get a lot of trailing zeros for small values.

Here's an example output of of %f

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

What I want is:

232
0.18
1237875192
4.58
0
1.2345

Sure I can write a function to trim those zeros, but that's lot of performance loss due to string manipulation. Can I do better with other format code?


The answers by Tom E. and Jeremy S. are unacceptable as they both arbitrarily rounds to two decimal places. Please understand the problem before answering.


Please note that String.format(format, args...) is locale-dependent (see answers below).

解决方案

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

Produces:

232
0.18
1237875192
4.58
0
1.2345

And does not rely on string manipulation.

这篇关于如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆