在Java中将双精度显示到一定精度 [英] Displaying doubles to a certain precision in java

查看:120
本文介绍了在Java中将双精度显示到一定精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个计算器应用程序.我知道双精度不是良好数学的最佳选择.该应用程序中的大多数功能都具有很高的精度,但不会获得非常难看的结果.我的解决方案是仅向用户显示12位小数的精度.我选择12是因为我的最低精度来自我的数值推导函数.

I am currently writing a calculator application. I know that a double is not the best choice for good math. Most of the functions in the application have great precision but the ones that don't get super ugly results. My solution is to show users only 12 decimals of precision. I chose 12 because my lowest precision comes from my numerical derive function.

我遇到的问题是,如果我将其乘以缩放器,然后四舍五入然后除以缩放器,则精度极有可能被淘汰.如果我使用DecimalFormat,则无法仅显示12并正确显示用于科学计数法的E,但如果不需要,则无法显示.

The issue I am having is that if I multiply it by a scaler then round then divide by the scaler the precision will most likely be thrown out of whack. If I use DecimalFormat there is no way to show only 12 and have the E for scientific notation show up correctly, but not be there if it doesn’t need to be.

例如我想要

1.23456789111213 to be 1.234567891112

但从不

1.234567891112E0

但我也想要

1.23456789111213E23 to be 1.234567891112E23

所以基本上我想将数字的字符串格式化为12位小数,以保留科学计数法,但是在不应该使用的时候就不科学

So basically I want to format the string of a number to 12 decimals places, preserving scientific notation, but not being scientific when it shouldn't

推荐答案

使用String.format("%.12G", doubleVariable);

这就是使用format()以科学计数法显示值的方式,但是如果不需要,则无需科学计数法.一个警告是,您在"E"之后以"+"结尾,因此您的结尾将像1.234567891112E + 23

That is how you use format() to display values in scientific notation, but without the scientific notation if not needed. The one caveat is that you end up with a '+' after the 'E', so yours would end up like 1.234567891112E+23

这篇关于在Java中将双精度显示到一定精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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