The Dude
The Dude

Reputation: 320

Displaying doubles to a certain precision in 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

Upvotes: 2

Views: 3725

Answers (3)

lukastymo
lukastymo

Reputation: 26799

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.

Upvotes: 0

Justin Waugh
Justin Waugh

Reputation: 4163

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

Upvotes: 3

Stian Storrvik
Stian Storrvik

Reputation: 2199

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.

Upvotes: 0

Related Questions