How to determine if string from file is float or double in C++?

  • A+
Category:Languages

I would like to parse a file and determine if the number I've read is float or double. The file I parse is one of the matrices in Matrix Market format (like this: https://sparse.tamu.edu/HB/1138_bus).

Basically the inputs are in this order: int int float (or double):

1138 1138 2596 1 1 1474.779 5 1 -9.017133 563 1 -5.730659 2 2 9.136654 10 2 -3.405995 

etc...

When I read the float number I would like to determine if the number can be stored in float or it needs something big, like double.

Is there some best way of reading and at the same time determining if string can be stored in float or double?

 


The problem with reading decimal values is that it's not easy to tell just by looking at them whether a float has enough precision or not.

For example, 1.0009765625 will fix exactly in a float but 1.1 won't exactly fit in a double (or any binary floating point type).

You're best off always using double when reading in floating point types. float should in general be avoided unless you have a very specific reason for doing so.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: