java - If the result of a double is divisible by another double is accurate? -


i know float , double not accurate.i have question this.

double a=4.0/2.0; system.out.println(a); 

the output 2.0. whether result accurate or not. question comes when read book java programming language. shows me method set scale of output this.

system.out.println((int)(area*100)/100.0); 

the statement set output 2 decimal places.and know floating-point arithmetic not accurate.so can statement work?

in first case, result 2.0. reason 4.0 , 2.0 both representable java doubles. divide operator returns closest double real number division result, 2.0.

in second case, whether exact result or not depend on value of area. representable 2 decimal place doubles end in .00, .25, .50, or .75. remaining 2 decimal place doubles can approximated.

the cast int causes inaccuracies, , should replaced math.round. problem positive double less integer casts next integer down, rounds closest integer. here program illustrating issue:

import java.math.bigdecimal;

public class test {   public static void main(string[] args) {     double area = 0.29;     system.out.println(new bigdecimal(area));     system.out.println(new bigdecimal(area*100));     system.out.println(new bigdecimal((int)(area*100)/100.0));     system.out.println((int)(area*100)/100.0);     system.out.println(math.round(area*100)/100.0);   } } 

output:

0.289999999999999980015985556747182272374629974365234375 28.999999999999996447286321199499070644378662109375 0.2800000000000000266453525910037569701671600341796875 0.28 0.29 

the closest double 0.29 smaller it, , result of multiplying 100 less 29. casting int gets 28, rounding gets 29.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -