Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to float in Java without round it [duplicate]

Tags:

java

Possible Duplicate:
Rounding in java Float.parseFloat

I want to convert strings to float i say:

System.out.println(Float.parseFloat("1553781.9829"));

Output:

1553782.0

I say:

System.out.println(Float.valueOf("1553781.9829"));

Output:

1553782.0

How to get Float without lossing precision?

like image 278
Kliver Max Avatar asked Dec 26 '12 07:12

Kliver Max


2 Answers

use System.out.println(Double.parseDouble("1553781.9829")); instead

float has a limitation of smaller size (4 bytes) so it's not good for big decimals, double has the double size (8 bytes)

like image 87
vishal_aim Avatar answered Sep 26 '22 01:09

vishal_aim


If you are looking for accuracy, I would suggest BigDecimal

This is just like normal wrapper class which provides methods for all your operations. And yes it takes argument as String as well.

  BigDecimal bd = new BigDecimal("1553781.9829");
  System.out.println(" bd :"+ bd);  //prints the same value

URL : http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

like image 21
rai.skumar Avatar answered Sep 26 '22 01:09

rai.skumar