PDA

View Full Version : All digits of float to QString



timmu
4th January 2012, 05:04
Hi,

I need to convert float to QString so that all original digits (including 0's) are preserved. In the example below 100.0 becomes 100 and I don't want that. How would I do the conversion so that all digits are preserved?

The example shows where my floating number comes from and where it needs to go. I know it seems like running in a circle but my script requires this.


char TestChar[]="100.0";
QString MyChar = TestChar;
float TestFloat = MyChar.toFloat();

QString float_to_text;
float_to_text.setNum(TestFloat);


Alternatively I'd like to know what is the best way to tell if an entry from a file is int or float? Does Qt offer such function? I'd like it to recognize "100.0" as a float.

Thanks!

ChrisW67
4th January 2012, 07:20
You can format a number as a string with a specified number of decimal places using QString::number() and the 'f' format (or its QLocale equivalent). If you need to present exactly what the user entered back to the user then keep it as a string. Once you convert it to float you have no way to distinguish between "100", "100.0" and "100.00000": 100 is 100 (and integer) no matter how many zeros you append after the decimal point.

Recognising a string as a floating point or integer number is not trivial unless you restrict yourself to one location. For example, "1,100.0" is a number in some locales and not others where it may be expressed as "1.000,0" or "1000.0". You could use a simple regular expression to tell "100.0" apart from "100" but you have to know exactly what your input might look like. What would you do with 1100 expressed as "1.1e3" or "100." for example?