Reputation: 47
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!
Upvotes: 1
Views: 45
Reputation: 158
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;
}
Upvotes: 2
Reputation: 4333
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;
}
Upvotes: 1