不要使用double來(lái)構(gòu)造一個(gè)BigDcimal對(duì)象。BigDecimal的構(gòu)造函數(shù)有這么一段說(shuō)明:
- 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作為構(gòu)造函數(shù)參數(shù),也會(huì)導(dǎo)致BigDecimal對(duì)象不精確,比如使用浮點(diǎn)數(shù)0.1來(lái)構(gòu)造一個(gè)BigDecimal對(duì)象,它的實(shí)際值為0.1000000000000000055511151231257827021181583404541015625,所以,需要精確計(jì)算的場(chǎng)景,推薦使用String類型的構(gòu)造函數(shù)。
總之,在需要精確浮點(diǎn)數(shù)計(jì)算的場(chǎng)景,