- 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类型的构造函数。
总之,在需要精确浮点数计算的场景,不要在任何地方使用double,float类型的变量,应该使用String类型来创建BigDecimal.