本文介绍了BigDecimal初始化后的Stange值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以以下方式初始化HashMap:

I'm trying to initialize a HashMap in the foolowing way:

HashMap<BigDecimal,BigDecimal> myMap = new HashMap<>();
myMap .put(new BigDecimal(1.7), new BigDecimal(1.5));
myMap .put(new BigDecimal(3.3), new BigDecimal(3));
myMap .put(new BigDecimal(5), new BigDecimal(4.5));
myMap .put(new BigDecimal(6.6), new BigDecimal(6));
myMap .put(new BigDecimal(11), new BigDecimal(10));
myMap .put(new BigDecimal(16.5), new BigDecimal(15));

但是插入上方的tha值在以下wang中发生了变化:

but tha value above insert are change in the following wang:

1.7 becomes 1.6999999999999999555910790149937383830547332763671875
3.3 becomes 3.29999999999999982236431605997495353221893310546875
6.6 becomes 6.5999999999999996447286321199499070644378662109375

为什么会这样?

推荐答案

使用 BigDecimal.valueOf(double)静态方法:这将从字符串的表示形式初始化 BigDecimal 您需要的双精度数字.

Use BigDecimal.valueOf(double) static method: this will initialize the BigDecimal from string representation of the double number which is what you need.

这篇关于BigDecimal初始化后的Stange值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:56
查看更多