0

I have a line of code in a for loop which formats a function ( that returns a float) return value into the appropriate format to be used. QString Value essentially stores the formatted value.

QString Value;

For(int i = 0; i < NUM; i++) {

Value.sprintf("%1.f", GetValue(0,i)); //need this value 

} 

Now this gives me the value I need in the correct form, however I require it to be a floating point number to be used. I have tried conventional means such as sstream, type cast and static cast but none have worked

Any help is appreciated and feel free to ask more questions for clarification and I will do my best to respond.

Adam Gong
  • 41
  • 5
  • 1
    What is the type returned by `GetValue` ? Please post a [mre]. – wohlstad Aug 31 '23 at 04:29
  • 1
    A side note: `QString::sprintf` is obsolete. See: https://doc.qt.io/qt-5/qstring-obsolete.html#sprintf. According to the documentation: _"Use asprintf(), arg() or QTextStream instead."_. – wohlstad Aug 31 '23 at 04:32
  • [QString.toDouble()](https://doc.qt.io/qt-5/qstring.html#toDouble). It's effectively a dup – Ken Y-N Aug 31 '23 at 04:34
  • Does this answer your question? [QString to double](https://stackoverflow.com/questions/43685944/qstring-to-double) – Ken Y-N Aug 31 '23 at 04:35
  • 2
    Is the string needed to begin with? Why not convert the result of `GetValue` directly to a floating point number? What is the actual problem you're trying to solve? Right now, your question is too much of an [XY problem](https://en.wikipedia.org/wiki/XY_problem) (besides missing other crucial information). – Some programmer dude Aug 31 '23 at 04:35
  • @Someprogrammerdude So the function does return a float, but I need to format it into a string to get the value I need then back to a float. Essentially I need ` Value.sprintf("%1.f", GetValue(0,i)) ` to be a float value. – Adam Gong Aug 31 '23 at 05:59
  • So essentially you want to *round* it to one decimal? Then multiply iyt by `10.0`, call [`std::round`](https://en.cppreference.com/w/cpp/numeric/math/round) to get the nearest integer value, and then divide by `10.0` again. ***But*** note that the value might not be perfectly representable as an exact floating point value (see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)), and it still might not be a single decimal. You will have the exact same problem if going through a string. – Some programmer dude Aug 31 '23 at 06:40
  • So basically, no matter what method you use, you still might not get the single decimal digit you want. Which brings us back to the actual, underlying and original problem you think this rounding would solve. Please ask about that *directly* instead. – Some programmer dude Aug 31 '23 at 06:42

0 Answers0