java 双精度输入,在Java中将双精度显示到一定精度

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值