M
M
mxr2022-03-07 19:14:06
C++ / C#
mxr, 2022-03-07 19:14:06

Is it correct to compare numbers declared as strings, i.e. with a string object?

Can there be any problems (data loss, rounding, etc.) with such a comparison.
How does the compiler behave in the situation below?

int main() {

  string num_in_str = "100.05";
  string num_in_str2 = "100.03";

  if (num_in_str < num_in_str2) {
    // ...
  }

        return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2022-03-07
@mxr

How does the compiler behave in the situation below?

The compiler inserts a call to string::operator <. If it is a std::string, then the operator performs a lexicographic comparison, i.e. compares the characters of both strings in turn up to the first different pair, the smaller one will be the string to which the character with the lower code belongs.
In the example "100.05" < "100.03" the result will be false because 5 > 3.
Can there be any problems

For such a comparison, string representations of numbers must begin with digits of the same weight. Those. you can compare "100.05" and "099.1" (the first digit on the left and right are hundreds), but you cannot compare "100.05" and "99.1" (the first digit on the left is hundreds, on the right is tens).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question