Best Java Object for Incredibly Small Decimals
What java object is best suited to hold tiny decimal values, such as 10^-25? What object will maintain the value of the number most accurately, while using the least space?
I simply need to store the value for display, not use it for any calculations. Are there other alternatives I co开发者_开发技巧uld use?
Store it as a String. There's no need to use numerical data types if you aren't doing calculations.
If you truly don't need to do any calculations with these values, a String
would be hacky but sufficient. Alternately, you could use the arbitrary-precision java.math.BigDecimal
class.
BigDecimal
will do just fine.
BigDecimal dec = BigDecimal.valueOf(1, -25);
The main reason to prefer this over a String is because you can change/customize your format. If you keep it as a String, it will be stuck in whatever format it originally had until you parse it, meaning you can't do localization, etc.
You can use double and if not enough, you also have the BigDecimal class. However, if you are not computing anything, I would simply store them as strings in the way I receive them.
There's always a tradeoff of space vs. precision when dealing with decimal numbers. Floats (and doubles) have less accuracy in the extreme ends of their ranges, but are more space efficient than, say, BigDecimal. And they can generate infinite series when representing certain numbers (like 0.1).
Go with BigDecimal.
BigDecimal will be perfectly accurate but use (comparatively) a lot of space. Just a plain old primitive double will give you 15 digits of precision, so unless you need absolutely exact values (as in financial calculations), I'd say double is your best bet
精彩评论