-2

I have an address domain , which has fields lat and long as BigDecimal and i am using constraints of scale as 16. I have this address

550 Tremont St, Boston, MA 02116, USA

its long and lat are -71.07126540000002 and 42.3438919

Longitude for this address is stored in db as -71.0712654000000200. now i need to compare the saved longitude with any new request to check if longitude already exist.

I am sending the same longitude again -71.07126540000002 but i am not able to convert it the form as it saved in db (-71.0712654000000200) before comparing as they are the long. of same address.

i tried using

BigDecimal a = new BigDecimal(-71.07126540000002)
println a.setScale(16,  RoundingMode.CEILING)​ // tried all other RoundingMode

but all are giving response as either -71.0712654000000156 or -71.0712654000000157 but not getting -71.0712654000000200

Help!

Not Known
  • 55
  • 8
  • It appears to me that both values have 7 digits of precision and the rest is just error. Round to 16 decimal places isn't appropriate when you have 15-16 digits of precision. – Peter Lawrey Oct 24 '16 at 10:51
  • 2
    Do this for exact representation: `BigDecimal a = new BigDecimal("-71.07126540000002")`. Doubles have no exact representation for the decimal part. – TT. Oct 24 '16 at 10:52
  • It's a bit ridiculous to look for an exact match. The numbers you have given are several orders of magnitude less than a micrometer apart. For all practical reasons that's the same location. – Henry Oct 24 '16 at 10:59
  • 1
    Even at the equator, 5 decimal places are accurate to about a metre. Do you really need more accuracy than this? (AKA I'm willing to bet your values you have for the location are nothing like as precise as you are suggesting) – Phylogenesis Oct 24 '16 at 11:01

2 Answers2

2

You can also just use BigDecimal notation:

-71.0712654000000200000g​.setScale(16) or ​-71.07126540000002000000G.setScale(16)

Both result in:

-71.0712654000000200

Another option is setting a custom MathContext.

1

It should be used

a.setScale(14, RoundingMode.HALF_UP)

since after 14th pos. zeros are not significative

at the end will be -71.07126540000002

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97