-2

I am trying to parse string to float but it gives me some different output. Suppose my code :

String a = "111111111111111111111.23";
Float f = Float.parseFloat(a);
System.out.println(f);

It gives me something like: 1.1111111E20

In a simple manner, it gives me 111111110000000000000

How do I get all the data shown? I do not want to truncate the input data.

Tom
  • 16,842
  • 17
  • 45
  • 54
user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
  • http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0 – Reg Jun 18 '15 at 08:46
  • Use Double or BigDecimal instead float has a limitation of smaller size (4 bytes – Hiren Jun 18 '15 at 08:46
  • 2
    Hint: please study a bit more about the representation of numbers using computer systems. If you really rely on "representing data as it is" ... you should really **understand** what that means. And as you are not a newbie: why didn't you do that prior research prior to posting a question here? – GhostCat Jun 18 '15 at 08:49

2 Answers2

6

How to get whole data as it is. Don't want to truncate the input data.

Then whatever you do, don't use a float. At least use double, but even double will struggle with that value as IEEE-754 double-precision floating point numbers are only precise to roughly 15 digits when expressed in base 10. For greater precision than that, look at BigDecimal.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Does `BigDecimal` support floating ? – user3145373 ツ Jun 18 '15 at 08:43
  • @user3145373ツ: `BigDecimal` supports floating-point operations, if that's what you mean. – T.J. Crowder Jun 18 '15 at 08:44
  • @user3145373ツ You can check that here: [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html) – Tom Jun 18 '15 at 08:44
  • I have tried `BigDecimal m = new BigDecimal(a);` , it gives me `111111111111111110000`. is it expected ? – user3145373 ツ Jun 18 '15 at 08:50
  • I am returning this data to view using json, i think that's why problem occurs. Otherwise I am also getting exact value as it is. But it's json parsing problem i think. – user3145373 ツ Jun 19 '15 at 01:25
  • @user3145373ツ: What parsing library are you using? Does it have the option of getting the value as a `BigDecimal`? If not, you may have to change the JSON to send these values as strings and then parse them yourself after retrieving them as strings. – T.J. Crowder Jun 19 '15 at 06:45
2

BigDecimal never rounds automatically or loses precision it is highly preferred in calculations.

A float is a decimal numeric type represented with 32 bit.

A double is a 64 bit decimal number, so it can represent larger values than a float.

You can Use BigDecimal

public static void main(String[] args) {
        String a = "111111111111111111111.23";
        BigDecimal f = new BigDecimal(a);
        System.out.println(f);
    }

Output

111111111111111111111.23
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116