开发者

Convert decimal dollar amount from string to scaled integer

"35.28" is stored as a char*. I need to turn it into an integer (35280).

I want to开发者_如何学C avoid floats. How can I do this?


Minimal basic code:

std::string s = "35.28";
s.erase(std::remove(s.begin(), s.end(), '.'), s.end()); //removing the dot
std::stringstream ss(s);
int value;
ss >> value;
value *= 10;
std::cout << value;

Output:

35280

Online demo : http://ideone.com/apRNP

That is the basic idea. You can work on the above code to make it more flexible so that it can be used for other numbers as well.


EDIT:

Here is one flexible solution:

int Convert(std::string s, int multiplier) 
{
   size_t pos = s.find('.');
   if ( pos != std::string::npos)
   {
       pos = s.size() - (pos+1);
       s.erase(std::remove(s.begin(), s.end(), '.'), s.end());
       while(pos) { multiplier /= 10; pos--; }
   }
   else
        multiplier = 1;
   std::stringstream ss(s);
   int value;
   ss >> value;
   return value * multiplier;
}

Test code:

int main() {
      std::cout << Convert("35.28", 1000) << std::endl; //35.28 -> 35280
      std::cout << Convert("3.28", 1000)  << std::endl; //3.28  -> 3280
      std::cout << Convert("352.8", 1000) << std::endl; //352.8 -> 352800
      std::cout << Convert("35.20", 1000) << std::endl; //35.20 -> 35200
      std::cout << Convert("3528", 1000) << std::endl;  //no change
      return 0;
}

Output:

35280
3280
352800
35200
3528

Online Demo : http://ideone.com/uCujP


Remove dot char from string and convert it directly to int


Do you mean stored as a string (char*)? Then you can create your own parser:

int flstrtoint(const char *str) {
    int r = 0;
    int i = strlen(str) - 1;

    while (i >= 0) {
        if (isdigit(str[i])) {
            r *= 10 
            r += str[i] - `0`;
        }
        i--;
    }

    return r;
}

flstrtoint("35.28"); // should return 3528


Remove the dot from the char and then
Simplest but not the best use atoi

See my answer here, for other possible ways.


As Als sais, use atoi, but with a twist, strip the string of the period and convert the result into int using atoi.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜