Handling numbers with many values ​​after a decimal in Java

I do

Collections.frequency(List<String>, List<String>.get(i)) / List<String>.size() 

The conclusion for the above calculation should be (for example)

 0.00631 0.0002378 0.00571 

but instead I get 0.0 . How can I handle this? I keep getting 0.0 with double and float

thanks

+4
source share
2 answers

If the values 0.00631 , 0.0002378 and 0.00571 are the expected results from the divisions, make sure that you are not doing whole divisions. That is, make sure that the numerator or denominator is floating or doubling.

Instead

 double fraction = someInt / someOtherInt; 

You can do

 double fraction = (double) someInt / someOtherInt; 

In your particular case, you can try something like

 (double) Collections.frequency(list, list.get(i)) / list.size(); 
+7
source

Use BigDecimal , which does not introduce rounding for very large or very small numbers by increasing memory consumption and slower calculations. This class is required for any financial data.

 BigDecimal val = new BigDecimal("10000000000000.0002378"); System.out.println(val); 
0
source

All Articles