Displaying doubles to a certain precision in java

2019-07-17 20:52发布

问题:

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

回答1:

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



回答2:

I think you're looking for the BigDecimal class. You can use the toEngineeringString() method, to get the scientific notation. Also see this answer. You can also set the precision of a BigDecimal, by specifying the MathContext in its constructor, or the scale by using one of the setScale() methods.



回答3:

String.format("%.12d", doubleVariable);

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.



回答4:

You'll be interested in BigDecimal, for example:

BigDecimal number = new BigDecimal("1.23456789111213");
number = number.setScale(12, RoundingMode.HALF_UP);
System.out.println(number);

Choose appropriate to you RoundingMode.