Friday, July 5, 2019

Java Decimal Round of Understanding:

double[] doubleList= {
        0.001,
        0.0012,
        0.00123,
        0.001234,
        0.0012345,
        0.1234567,
        0.0000001,
        0.0000005,
        0.0000006,
        0.0000009,
     1234.00000001,
        0.00000005,
        0.00000006,
        0.00000009,
        0.111111111,
        0.000000005,
        0.000000006,
        0.000000009,
        1.9,
        0.09,
        0.009,
        0.00999,
        0.009999,
        0.0099999,
        0.00999999,
        0.999999999};
for (double d:doubleList) {
    System.out.println("   round7: "+roundOfForBilling(d)+" val="+d );
}
public static double  roundOfForBilling(double value) {
    DecimalFormat df = new DecimalFormat("0.0000000");
    df.setRoundingMode(RoundingMode.UP);
    //df.setMaximumFractionDigits(7);    
    System.out.print(" format:"+df.format(value)+
                     " rm="+df.getMaximumFractionDigits());
    return Double.parseDouble(df.format(value));
}
Output:
 format:0.0010000 mode=UP   round7: 0.001     val=0.001
 format:0.0012000 mode=UP   round7: 0.0012    val=0.0012
 format:0.0012300 mode=UP   round7: 0.00123   val=0.00123
 format:0.0012340 mode=UP   round7: 0.001234  val=0.001234
 format:0.0012345 mode=UP   round7: 0.0012345 val=0.0012345
 format:0.1234567 mode=UP   round7: 0.1234567 val=0.1234567
 format:0.0000001 mode=UP   round7: 1.0E-7    val=1.0E-7
 format:0.0000005 mode=UP   round7: 5.0E-7    val=5.0E-7
 format:0.0000006 mode=UP   round7: 6.0E-7    val=6.0E-7
 format:0.0000009 mode=UP   round7: 9.0E-7    val=9.0E-7
 format:1234.0000001 mode=UP   round7: 1234.0000001 val=1234.00000001
 format:0.0000001 mode=UP   round7: 1.0E-7    val=5.0E-8
 format:0.0000001 mode=UP   round7: 1.0E-7    val=6.0E-8
 format:0.0000001 mode=UP   round7: 1.0E-7    val=9.0E-8
 format:0.1111112 mode=UP   round7: 0.1111112 val=0.111111111
 format:0.0000000 mode=UP   round7: 0.0       val=5.0E-9
 format:0.0000000 mode=UP   round7: 0.0       val=6.0E-9
 format:0.0000000 mode=UP   round7: 0.0       val=9.0E-9
 format:1.9000000 mode=UP   round7: 1.9       val=1.9
 format:0.0900000 mode=UP   round7: 0.09      val=0.09
 format:0.0090000 mode=UP   round7: 0.009     val=0.009
 format:0.0099900 mode=UP   round7: 0.00999   val=0.00999
 format:0.0099990 mode=UP   round7: 0.009999  val=0.009999
 format:0.0099999 mode=UP   round7: 0.0099999 val=0.0099999
 format:0.0100000 mode=UP   round7: 0.01      val=0.00999999
 format:1.0000000 mode=UP   round7: 1.0       val=0.999999999

RoundingMode.UP
RoundingMode.DOWN        we use this more 0.00000 you will find
RoundingMode.HALF_UP     (but this reduce)
RoundingMode.HALF_EVEN

No comments: