Java:如何格式化具有第十个指数的字符串数字
我有一个数字作为字符串,如下所示:“9.756088256835938E-4”,但我只能使用指定数量的字符(在这种特殊情况下为 9 个字符)。所以我想要这样的东西:“9.7561E-4”。我已经尝试将字符串转换为双精度,然后使用格式方法来获得更少的字符,但我没有得到正确的解决方案。
问题是我需要十个指数输出,因为有些数字比我拥有的字符数长。如果可能的话,数字应该不显示十指数,如果不行就使用十指数。
正确的舍入也很好。
它应该适用于负数。 (减号需要一个字符!!!)
是否有一种格式函数可以定义输出字符串的最大长度?有什么想法吗?
I have a number as a string like this: "9.756088256835938E-4" but I only can use a specified number of characters (in this special case 9 char). So I want to have something like this: "9.7561E-4". I already tried to convert the String to a Double and then used the format method to get a less characters but I don't got a correct solution.
The problem is that I need ten exponential output since some numbers are longer than the number of characters I have. If it is possible, the number should be displayed with no ten exponent, if not just use the ten exponent.
Also correct rounding would be good.
And it should work for negative numbers. (minus needs one character!!!)
Is there a format function where I can define the maximum length of the output string? Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法找到一个可以涵盖您描述的所有情况的单一格式模式。但我认为这是一个有效的逻辑组合:
模式中的“G”指示格式化程序在允许相同或更好的精度时放弃使用指数。我们增长到最大长度,并在输出字符串达到 10 个字符时停止。我认为您可以对
DecimalFormat
采取相同的方法,但我更熟悉Formatter
。I'm having trouble findind a single format pattern that will cover all of the cases that you described. But here's a combination of logic that I think works:
The "G" in the pattern instructs the formatter to forego the use of the exponent when it will allow for the same or better precision. We grow up to the maximum length and stop when our output string is 10 characters. I think you could take the same approach with a
DecimalFormat
, but I'm more familiar withFormatter
.看到马克的示例满足您的要求,我更新了我的答案以显示
DecimalFormat
实现。我使用了马克的测试用例。这绝对是一个更丑陋的选择,因为没有简单的方法来打开/关闭指数。与String.format
选项相比的唯一优点是它可以很好地处理非常小的数字。这让我想起了类似问题,OP 的数字只有 5 个左右的空格,并且只有在有足够的空间时才想显示小数。但不想使用指数,而是想使用后缀(k,m等)
Seeing the Mark's example meet your requirements, I updated my answer to show the
DecimalFormat
implementation. I used Mark's test cases. It is definitely an uglier option because there is no easy way to turn on/off exponents. The only advantage over theString.format
option is that it handles very small numbers well.This reminded me of a similar question where the OP only had 5 or so spaces for a number and wanted to show a decimal only when there was enough space. But instead of exponents, wanted to use a suffix of (k,m, etc)