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

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

问题描述

64位双精度数可以准确表示整数+/- 2 53 .

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

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

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.

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

So how do I print these doubles nicely in Java?

我尝试了String.format("%f", value),它很接近,除了对于小值,我会得到很多尾随零.

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

这是%f


232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

我想要的是:


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?

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

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.

请注意,String.format(format, args...) 与语言环境相关的 (请参见下面的答案).

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);
}

产生:

232
0.18
1237875192
4.58
0
1.2345

并且不依赖于字符串操作.

And does not rely on string manipulation.

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

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