converting from float or double to QString results in output being 0
-
@Kent-Dorfman said in converting from float or double to QString results in output being 0:
so what is (float)5.7 / (int)10?
Umm, that would be
0.57
(not0
).... ! Dividing afloat
by anint
does not convert toint
! :) -
I stand corrected. I was certain the type of the denominator governed the result. Too much time in embedded kernel domain. D'Oh!
-
@Dean21 said in converting from float or double to QString results in output being 0:
msg_as_Qstring.remove(("[\u0000]."));
Why did you put [,] and dot there?
I suggested this:msg_as_Qstring.remove(QChar("\u0000"));
-
if in fact the conversion is being broken by the unicode null terminator then consider an intermediate conversion thru (char*) instead.
QString num(byteArray.data());
since char arrays have no defined length the constructor shoudl use the null as a string terminator, not as part of the string (as is the case when converting from a container that has an internal size field).
-
@Dean21
Glad it's working for you now. That's the steps I would have taken to get it working.@Kent-Dorfman said earlier
I question whether removing non-numeric char at end of QSTring is necessary for the numeric conversion problem since all the conversion code I'm familiar with scans digits until it finds an char that can't be part of the number, and then returns everything up to that point.
But, for whatever reason, conversions to numeric from
QString
state:Warning: The
QString
content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.So that's how they do it --- all characters in the string must be valid. You could use:
bool ok; double val = msg_as_Qstring.toDouble(&ok); if (!ok) qDebug() << "Conversion failed!";
-
@JonB said in converting from float or double to QString results in output being 0:
Warning: The QString content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.
In which case RTFM is the rule of the day! but I'm lazy.