在java中以一定精度显示双精度数
我目前正在编写一个计算器应用程序。我知道双精度数并不是良好数学的最佳选择。应用程序中的大多数函数都具有很高的精度,但有些函数不会得到非常难看的结果。我的解决方案是只向用户显示 12 位小数的精度。我选择 12 是因为我的最低精度来自我的数值导出函数。
我遇到的问题是,如果我将其乘以定标器,然后舍入,然后除以定标器,则精度很可能会失常。如果我使用 DecimalFormat,则无法仅显示 12 并正确显示科学记数法的 E,但如果不需要,则不会出现。
例如我想要
1.23456789111213 to be 1.234567891112
但从来没有
1.234567891112E0
但我也想要
1.23456789111213E23 to be 1.234567891112E23
所以基本上我想将数字的字符串格式化为小数点后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.
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.
for example I want
1.23456789111213 to be 1.234567891112
but never
1.234567891112E0
but I also want
1.23456789111213E23 to be 1.234567891112E23
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
String.format("%.12G", doubleVariable);
这就是如何使用 format() 以科学计数法显示值,但如果不需要,则不显示科学计数法。需要注意的是,“E”后面有一个“+”,因此您的结果将类似于 1.234567891112E+23
Use
String.format("%.12G", doubleVariable);
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
应该给你你在第一件事中寻找的东西。抱歉,我不知道如何定义何时显示您的电子通知。
Should give you what you are looking for in your first matter. I'm sorry but I don't know how to define when your E-notification is showed.
您会对 BigDecimal 感兴趣,例如:
选择适合您的 RoundingMode。
You'll be interested in BigDecimal, for example:
Choose appropriate to you RoundingMode.