Monday, 29 August 2016

Init. BigDecimal using string or float can give differences

It may initialize a BigDecmal by its constructor.  However, it may leave difference as using float type or string type.

The following experiment is able to approve it. You will see init. by the string gives the exactly same result, but using float will lead to a slight bias.


import java.math.BigDecimal;

/**
 *
 * @author YNZ
 */
public class UsingStringInit {

    public static void main(String[] args) {
        float f = 1000.1f; 
        BigDecimal bf = new BigDecimal(f);
        System.out.println("" + bf);
        
        double d = 1000.1d;
        BigDecimal bdd = new BigDecimal(d);
        System.out.println("" + bdd);
        
        String val = "1000.1";
        BigDecimal dd = new BigDecimal(val);
        System.out.println("" + dd);
    }
}


The output:
run:
1000.0999755859375
1000.1000000000000227373675443232059478759765625
1000.1
BUILD SUCCESSFUL (total time: 0 seconds)

The interesting is the decimal number "1000." will not exactly presented as BigDecimal is initialized by the float type.

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...