I have an XSD that requires me to use a BigDecimal for a lat/lon. I currently have the lat/lon as doubles, and convert them to BigDecimal, but I am only required to use about 12 places of precision. I have not been able to figure out how to set that. Can anyone help me with this?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Try this code ...
Result: 0.00000
You can use setScale() e.g.
This way you can set specific precision of a
BigDecimal
.The value of decPrec was
1.5726903423607562595809913132345426
which is rounded off to1.57267
.The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.
Some examples in Clojure.
(In Clojure, The
M
designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)You can easily increase the scale:
But you can't decrease the scale in the exact same way:
You'll need to pass a rounding mode too:
So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!
It is easy to decrease the precision:
But it is not obvious how to increase the precision:
For the skeptical, this is not just a matter of trailing zeros not being displayed:
FWIW, Clojure is careful with trailing zeros and will show them:
Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:
So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?
So, best I can tell, if you want to change precision, you'll need to do these steps:
These steps, as Clojure code:
I know, this is a lot of steps just to change the precision!
Why doesn't BigDecimal already provide this? Did I overlook something?