java - How can I make sure I am not going to get an integer cast when doing division? -


i find confusing try figure out when value computed double , when cast integer in java. example:

    system.out.println( 1 / 3 );     system.out.println( 1 / 3d );     system.out.println( 1d / 3 );     system.out.println( 1/ 1d / 3 ); 

produces:

0 0.3333333333333333 0.3333333333333333 0.3333333333333333 

am safe in assuming if there 1 double anywhere in expression whole expression double , if each , every value integer treated integer division?

to quote spec:

4.2.4. floating-point operations

if @ least 1 of operands numerical operator of type double, operation carried out using 64-bit floating-point arithmetic, , result of numerical operator value of type double. if other operand not double, first widened (§5.1.5) type double numeric promotion (§5.6).

15.17. multiplicative operators

the operators *, /, , % called multiplicative operators.

...

the type of multiplicative expression promoted type of operands.

if promoted type int or long, integer arithmetic performed.

if promoted type float or double, floating-point arithmetic performed.

so yes, safe in assuming resulting expression double if there @ least 1 double involved.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -