1

I am trying to correctly convert (parse) a string to float in java, for the number 5755.1115, example:

float fl = new BigDecimal("5755.1115").floatValue();
float fl = (float)5755.1115d;

The issue is that it always prints 5755.1113. It seems it loses precision (I also tried using MathcContext(10) for example but didn't work)

But if I try this in javascript it seems it is working:

var fl = parseFloat('5755.1115');
var str = "" + fl.toPrecision(8);
console.log("number: " + str);

It prints the number correctly even if I don't use toPrecision() function.

Can anyone explain how can I achieve this also in Java?

EDIT: My mistake, I forgot to specify that I do not want to use double because I need to keep the data transmission at minimum.

Andrei F
  • 4,205
  • 9
  • 35
  • 66
  • 1
    Why are you comparing Java and JavaScript? – Paul Nov 23 '17 at 08:52
  • 1
    Seems pretty evident that `5755.1113` is the closest `float` to `5755.1115`. You could use a `double` instead if it's not precise enough. – khelwood Nov 23 '17 at 08:55
  • I think it's because JavaScript only has double and 5755.1115 has too much precision for a float. – neuhaus Nov 23 '17 at 08:58
  • I forgot to specify that I do not want to use double because I need to keep the data transmission at minimum. (I edited my post) – Andrei F Nov 23 '17 at 09:31

2 Answers2

3

JavaScript only knows doubles. Calling toPrecision(8) on a JavaScript double won't change that.

[Not just in Java,] a float isn't big enough to store 5755.1115 accurately.

Can anyone explain how can I achieve this also in Java?

Use a double instead of a float if you need the extra precision.

neuhaus
  • 3,886
  • 1
  • 10
  • 27
  • I forgot to specify that I do not want to use double because I need to keep the data transmission at minimum. (I edited my post) – Andrei F Nov 23 '17 at 09:31
  • 1
    A float isn't big enough so you have to accept the loss in precision then or use something else. – neuhaus Nov 23 '17 at 09:42
2

For the java side: this here

float fl = new BigDecimal("5755.1115").floatValue(); 

is basically pointless. You first create a BigDecimal object (which allows for arbitrary precision) - to then turn that precise representation into a much "less precise" float value. You could as well write

float fl = 5755.1115f;

instead. Either you want to spend the overhead for "precise" BigDecimal - or you are happy with ordinary Java float floating point semantics. But mixing those two concepts like you are doing here is, as said: pointless.

GhostCat
  • 137,827
  • 25
  • 176
  • 248