8 Aralık 2023 Cuma

new BigDecimal() ve BigDecimal.valueOf() Farkı

Giriş
1. new BigDecimal(double) ile girdiğimiz değeri geri alamayabiliriz
2. BigDecimal.valueOf() ile girdiğimiz değeri geri alırız. 

Açıklaması şöyle
It’s all about how doubles are stored in binary. For instance, if you do new BigDecimal(0.1), you won’t just get 0.1. You’ll end up with a really precise value like 0.1000000000000000055511151231257827021181583404541015625. It’s because 0.1 can’t be perfectly represented in binary.
...
That’s why BigDecimal.valueOf is often preferred. It’s more about what you see and expect. But if you need extreme precision, like in scientific calculations, then new BigDecimal is your go-to.
1. new BigDecimal(doble) metodu
Açıklaması şöyle. BigDecimal double ile yaratılırsa verdiğimiz sayıyı geri alamayabiliriz
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.
Örnek
Şu kod farklı çıktı veriyor. Çünkü BigDecimal.valueOf(double) çağrısı double değeri shortest decimal representation kullanark String'e çeviriyor.
@Test
public void testUsingBigDecimal(){
  BigDecimal a = new BigDecimal(0.01);
  BigDecimal b = BigDecimal.valueOf(0.01);
  System.out.println("a = " + a);
  System.out.println("b = " + b);
}
//output
//a = 0.01000000000000000020816681711721685132943093776702880859375
//b = 0.01
Örnek
System.out.println(new BigDecimal(58.34));
Bu kod çıktı olarak 58.340000000000003410605131648480892181396484375 sayısını verir.
Çünkü 58.34 sayısı double ile tam temsil edilemez.

Örnek
BigDecimal bd = new BigDecimal(0.7d);
Çıktı olarak şunu alırız.
0.6999999999999999555910790149937383830547332763671875
2. BigDecimal.valueOf() metodu
Açıklaması şöyle
Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).
valueOf() alt tarafta şuna benzer bir şekilde çalışıyor. Verilen double sayıyı String'e çevriliyor. String'e çevrimde "shortest decimal representation" kullanıyor. Böylece 0.015 aslında double ile tam temsil edilemese bile String'e çevrimde 0.015 çıktığı için doğru BigDecimal değeri elde ediyoruz.
new BigDecimal (Double.toString(0.015))


Hiç yorum yok:

Yorum Gönder