0

The Answer come 0 and not 1, Why?

public class Student {

    public static void main(String[] args) {

        double s=1.3901863961920014E-5;
        int a= (int)s;
        System.out.println("a: "+a);
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • how it come 0 does not come 1 –  May 09 '18 at 09:10
  • 2
    How do you expect 0.00001 to be one ? You want to round up ? – azro May 09 '18 at 09:11
  • 1
    because, when casting a `double` into an `int`, you loose the decimal places. The exact behaviour is defined in [JLS §5.1.3](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3). – Turing85 May 09 '18 at 09:11

1 Answers1

4

because your number

1.3901863961920014E-5

Is :

0.000013901863961920014013868597546608185666627832688391208648681640625

You can try to check the full length like this :

double s = 1.3901863961920014E-5;
BigDecimal b = new BigDecimal(s);
System.out.println(b);
=> 0.000013901863961920014013868597546608185666627832688391208648681640625
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Impossigble to give better answer to very poor question – Jacek Cz May 09 '18 at 09:14
  • 1
    @JacekCz Which is why we often stay away from answering poor questions. But I am not the one to throw the first stone here ;-) ... and agreed, the answer is "good enough" now ... – GhostCat May 09 '18 at 09:15
  • How is there so many decimals on the Biginteger ? there is only about 17 in `s` but about 70 in `b` – azro May 09 '18 at 09:16
  • 1
    @azro http://www.phys.uconn.edu/~rozman/Courses/P2200_14F/downloads/floating-point-guide-2014-11-03.pdf – Dawood ibn Kareem May 09 '18 at 09:19
  • I want to show only two digit after dot, so how it possible –  May 09 '18 at 09:38
  • Two digits after the dot is ".00" – Kevin Anderson May 09 '18 at 09:40
  • @BhaveshTank there are many ways, for example `String.format("%.2f", s)` this will return a String `0,00`, or `b.setScale(2, BigDecimal.ROUND_HALF_UP)` but two 00 in after the dot doesn't make sense. take a look at this https://stackoverflow.com/questions/14515640/how-to-display-a-number-with-always-2-decimal-points-using-bigdecimal – Youcef LAIDANI May 09 '18 at 09:44
  • double s = 1.3901863961920014E-5; but output come in 0 ,how it possible to come up with.1.39 –  May 09 '18 at 09:55
  • @BhaveshTank why it should to come up `1.39` the full number you shared is `0,000013901863961920014` less than 1, so when you canst it to an int you get 0 and not another thing, or what you want exactly I don't get you! – Youcef LAIDANI May 09 '18 at 09:59
  • if you want 0.000013901863961920014 to display as 1.39, multiply it by 100,000 first. – Kevin Anderson May 09 '18 at 10:05