如何将浮点数更好地格式化为String,而不需要十进制0?

编程入门 行业动态 更新时间:2024-10-26 08:27:31
本文介绍了如何将浮点数更好地格式化为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?

本文发布于:2023-05-24 12:26:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   如何将   格式   更好地   浮点数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!