简体   繁体   English

Java的。如何在DecimalFormat中禁用舍入

[英]Java. How to disable rounding in DecimalFormat

Can I disable rounding "feature" in DecimalFormat? 我可以在DecimalFormat中禁用舍入“功能”吗?

For example: 例如:

DecimalFormat f = new DecimalFormat();

f.parseObject("123456789012345.99");

Result is 1.2345678901234598E14 结果是1.2345678901234598E14

java version "1.6.0_21" java版“1.6.0_21”

This is nothing to do with a feature of Java. 这与Java的功能无关。 It is due to the limited precision of IEEE 64-bit double floating numbers. 这是由于IEEE 64位双浮点数的精度有限。 In fact all data types have limits to their precision. 事实上,所有数据类型都有其精度限制。 SOme are larger than others. SOME比其他人大。

double d = 123456789012345.99;
System.out.println(d);

prints 版画

1.2345678901234598E14

If you want more precision use BigDecimal. 如果你想要更精确,请使用BigDecimal。

BigDecimal bd = new BigDecimal("123456789012345.99");
System.out.println(bd);

prints 版画

123456789012345.99

Even BigDecimal has limits too, but they are far beyond what you or just about any one else would need. 即使BigDecimal也有限制,但它们远远超出你或任何其他人所需要的。 (~ 2 billion digits) (约20亿位)

EDIT: The largest known primes fit into BigDecimal http://primes.utm.edu/largest.html 编辑:最大的已知素数适合BigDecimal http://primes.utm.edu/largest.html

No, that's not rounding, that's just the way floating point numbers work. 不,这不是四舍五入,这就是浮点数的工作方式。

The only way to do what you want is to use BigDecimal. 做你想做的事的唯一方法是使用BigDecimal。

I'd recommend that you read "What Every Computer Scientist Should Know About Floating Point Arithmetic". 我建议您阅读“每个计算机科学家应该知道的关于浮点算术的内容”。

As far as I understood, you want to print the number in special format. 据我所知,你想以特殊格式打印数字。 You need to call applyPattern(String Pattern) as here: 你需要调用applyPattern(String Pattern),如下所示:

  f.applyPattern(".000");
  System.out.println(f.format(123456789.99)); // prints 123456789.990

Note patterns are localised, eg in Germany it will print , instead of . 注意模式是本地化的,例如在德国它将打印,而不是。 to separate the fraction. 分开分数。 You can set the rounding preferrence via 您可以通过设置舍入偏好

f.setRoundingMode()

Guess where did I learn all this? 猜猜我在哪里学到了这一切? of course from Java docs . 当然来自Java文档 Read more about the pattern expression to format the way you like 阅读有关模式表达式的更多信息,以格式化您喜欢的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM