简体   繁体   中英

Reading 2 places after a decimal point in a string function

How would I read 2 digits after a period has been placed in a string? Instead of 3.146543 it would now be 3.14.

This is my current code:

string toCurrency(double &input) {
string output = "$";
string numberString = to_string(input);

for (auto singleChar : numberString) {
    output += singleChar;
    if (singleChar = '.') {

    }
}
return output;

Thanks in advance!

You can use old for loop:

string toCurrency(double &input) {
    string output = "$";
    string numberString = to_string(input);

    for (int i = 0; i < numberString.size(); ++i) {
        output += numberString[i];
        if (numberString[i] == '.') {
            output += numberString[i+1];
            output += numberString[i+2];
            break;
        }
    }
    return output;
}

You can simply create a bool and turn it true when you find the dot "." and a counter to count how many chars you pass after dot:

string toCurrency(double &input) {
    string output = "$";
    string numberString = to_string(input);
    int counter = 0;
    bool dot = false;

    for (auto singleChar : numberString) {
        output += singleChar;
        if (singleChar == '.')
           dot = true;
        if (dot) counter++;
        if (counter==3) break;
    }
return output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM