User can enter double
into textbox. Number might contain thousands separators. I want to validate user input, before inserting entered number into database.
Is there a C++ function that can convert such input (1,555.99
) into double
? If there is, can it signal error if input is invalid (I do not want to end up with function similar to atof
)?
Something like strtod
, but must accept input with thousands separators.
Convert the input to double using a stream that's been imbued with a locale that accepts thousand separators.
Here I've used the un-named locale, which retrieves locale information from the environment (e.g., from the OS) and sets an appropriate locale (e.g., in my case it's set to something like
en_US
, which supports commas as thousands separators, so:Of course, I could also imbue
std::cout
with some locale that (for example) uses a different thousands separator, and get output tailored for that locale (but in this case I've used the default "C" locale, which doesn't use thousands separators, just to make the numeric nature of the value obvious).When you need to do this with something that's already "in" your program as a string, you can use an
std::stringstream
to do the conversion:A C solution would be to use setlocale & sscanf: