-1

I have string representation of percentage change of a stock quote in the format +6.63 and some in -0.06, which i need to check is it a positive change or negative...

after splitting the string on + and - sign,

i can apply Float.parseFloat(stringWithNoSign);

but is there a way to extract the string as signed and convert to float

x-code
  • 608
  • 1
  • 10
  • 30

3 Answers3

1

You can directly use Float.parseFloat(stringWithSign) to convert back and forth.

If you still have problems with parseFloat you should consider your locale separator and try this solution.

Community
  • 1
  • 1
Bigger
  • 1,807
  • 3
  • 18
  • 28
0

Float.parseFloat() will parse the correct floating point number included the sign. This method internally uses Float.valueOf() which in turn transforms any valid java language float literal into a float type, of course including the ones you are dealing with.

Some info:

sdecima
  • 658
  • 6
  • 12
0

Float.parseFloat() will handle negative numbers, but float is imprecise, possibly leading to output with repeating decimals, where none existed in the original string, due to rounding issues internal to the way floats are stored.

For exact numbers, use the BigDecimal class, which will input, output and perform arithmetic without loss of precision.

Bohemian
  • 412,405
  • 93
  • 575
  • 722