如何将浮点数更好地格式化为String,而不需要十进制0? [英] How to nicely format floating numbers to String without unnecessary decimal 0?

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

问题描述

一个64位双倍可以表示整数+/- 2 53 精确

An 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 unsigned 32-bit.

但现在我必须打印这些伪整数,但问题是他们也是混合使用实际的双打。

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

当然我可以编写一个函数来修剪这些零,但是由于String是很多性能损失操纵。我可以用其他格式代码做得更好吗?

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 another format code?

编辑

Tom E.和Jeremy S.是不可接受的,因为他们任意轮回到小数点后两位。请在回答之前了解问题。

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

编辑2

请注意, code> String.format(format,args ...)是 区域设置相关的 (见下面的答案)。 >

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

推荐答案

如果这个想法是打印存储为双精度的整数,就像它们是整数,否则以最小必要精度打印双精度: / p>

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.

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

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