不要使用double來構造一個BigDcimal對象。BigDecimal的構造函數有這么一段說明:
- Theresultsofthisconstructorcanbesomewhatunpredictable.OnemightassumethatwritinginJavacreatesawhichisexactlyequalto0.1(anunscaledvalueof1,withascaleof1),butitisactuallyequalto0.1000000000000000055511151231257827021181583404541015625.Thisisbecause0.1cannotberepresentedexactlyasa(or,forthatmatter,asabinaryfractionofanyfinitelength).Thus,thevaluethatisbeingpassedintotheconstructorisnotexactlyequalto0.1,appearancesnotwithstanding.
- Theconstructor,ontheotherhand,isperfectlypredictable:writingcreatesawhichisexactlyequalto0.1,asonewouldexpect.Therefore,itisgenerallyrecommendedthattheStringconstructorbeusedinpreferencetothisone.
由于double本身是不精確的,如果使用double作為構造函數參數,也會導致BigDecimal對象不精確,比如使用浮點數0.1來構造一個BigDecimal對象,它的實際值為0.1000000000000000055511151231257827021181583404541015625,所以,需要精確計算的場景,推薦使用String類型的構造函數。
總之,在需要精確浮點數計算的場景,