java


Difference in BigDecimal behavior


I have two pieces of code new BigDecimal("1.240472701") and new BigDecimal(1.240472701). Now if i use compareTo method of java on both the methods then i get that they are not equal.
When i printed the values using System.out.println() method of java. I get different results for both the values. For example
new BigDecimal("1.240472701") -> 1.240472701
new BigDecimal(1.240472701) -> 1.2404727010000000664291519569815136492252349853515625
So i want to understand what could be reason for this?
Since user thegauravmahawar provided the answer from docs. Yes, it is because of Scaling in BigDecimal case.
So the values might seem equal to You but internally java uses Scaling while storing the value of BigDecimal type.
Reason: Scaling.
Improvement:
You could call setScale to the same thing on the numbers you're comparing:
like this
new BigDecimal ("7.773").setScale(2).equals(new BigDecimal("7.774").setScale (2))
This will save you from making any mistake.
You can refer the Java doc of public BigDecimal(double val) for this:
public BigDecimal(double val)
Translates a double into a BigDecimal
which is the exact decimal representation of the double's binary
floating-point value. The scale of the returned BigDecimal is the
smallest value such that (10^scale × val) is an integer.
The results of this constructor can be somewhat unpredictable. One
might assume that writing new BigDecimal(0.1) in Java creates a
BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with
a scale of 1), but it is actually equal to
0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that
matter, as a binary fraction of any finite length). Thus, the value
that is being passed in to the constructor is not exactly equal to
0.1, appearances notwithstanding.
The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates
a BigDecimal which is exactly equal to 0.1, as one would expect.
Therefore, it is generally recommended that the String constructor be
used in preference to this one.
When a double must be used as a source
for a BigDecimal, note that this constructor provides an exact
conversion; it does not give the same result as converting the double
to a String using the Double.toString(double) method and then using
the BigDecimal(String) constructor. To get that result, use the static
valueOf(double) method.
The string "1.240472701" is a textual representation of a decimal value. The BigDecimal code parses this and creates a BigDecimal with the exact value represented in the string.
But the double 1.240472701 is merely a (close) approximation of that exact decimal value. Double cannot represent all decimal values exactly, so the exact value stored in the double differs slightly. If you pass that to a BigDecimal, it takes that differing value and turns it into an exact BigDecimal. But the BigDecimal only has the inexact double to go by, it does not know the exact text representation. So it can only represent the value in the double, not the value of the source text.
In the first case:
String --> BigDecimal
Because BigDecimal is made to exactly represent decimal values, that conversion is exact.
In the second case:
1 2
Source code text --> double --> BigDecimal
In the second case, precision is lost in the first conversion (1). The second conversion (2) is exact, but the input -- the double -- is an inexact representation of the source code text 1.240472701 (in reality, it is 1.2404727010000000664291519569815136492252349853515625).
So: never initialize a BigDecimal with a double, if you can avoid it. Use a string instead.
That is why the first BigDecimal is exact and the second is not.

Related Links

Spring exception in apache cxf rest service
Split String by +-/* and keep all other special characters [duplicate]
When Shoud i override other function of Exception in Java?
how to rename an extracted file
Dependent jar classes not getting loaded from URLClassloader
Why 1st print statement did'nt print RID?
Local variable not initialized, but still program compiling
Server Sent Event Client with additional Cookie
Spring JMX Integration Issue
Java EE + Wildfly 9: Use directory outside the deployed app for upload
Calendar getTimeInMillis difference of 1 hour
MessageDigest.isEqual function use in Java
I have been tasked to create a foodstore that I can add and take food from, does my code achieve this?
How to determine when HttpClient creates a new connection
How to create signature capture for android application [duplicate]
Download a file in browser using java /spring

Categories

HOME
netsuite
keycloak
push-notification
iterator
alfresco
at-command
dxl
pivotal-cloud-foundry
fancybox
django-imagekit
vault
node-pdfkit
rascal
decimal
progressive-web-apps
scriptcs
jquery-ajaxq
realex-payments-api
mmap
devops
jndi
lcd
hammerspoon
blazemeter
firebase-crash-reporting
p-value
sparse-matrix
semantic-analysis
spring-mybatis
.net-4.0
semantic-versioning
google-qpx-express-api
winrt-xaml-toolkit
amazon-kinesis-kpl
environment-modules
appfabric
main
automake
abstract-class
android-fingerprint-api
trim
broadcastreceiver
janrain
http-live-streaming
android-mediaprojection
netcdf4
reactive-cocoa-5
executenonquery
scorm
smartcontracts
upstart
pango
errordocument
domain-model
magma
pg-dump
libusb-win32
dtexec
zendesk-app
orthogonal
gnome-shell-extensions
google-cdn
ctest
django-debug-toolbar
holder.js
flash-cs5
pyke
libressl
interrupted-exception
sysinternals
census
oberon
csquery
ng-animate
websocket4net
php-5.4
has-many-through
aapt
fluentautomation
htmlcleaner
marmalade
mysql-error-1062
fmod
farseer
gwt-rpc
angularjs-controller
pvrtc
path-separator
objective-c-2.0
parametric-equations
punbb
hgsubversion
cufon
custom-backend
whoosh
vdsp
appender
fluent-interface
asp.net-mvc-areas
coda-slider
filtered-index
meego
ti-dsp
noscript
lzh
misv

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App