Verify if juce::String is a number


I am totally sorry, I know its stupid question. I know how to find if std::string is a digit or not.
With something like that:

bool is_number(const std::string& s)
    return !s.empty() && std::find_if(s.begin(), 
        s.end(), [](char c) { return !std::isdigit(c); }) == s.end();

But when I try to do it with juce::String I get error “in String there is no member begin()”.

So I suppose there is some simpler solution but can’t find it.


Within your initial specification, something like :

bool is_number(const String& str)
	return str.containsOnly("0123456789.-");


Thanks, great,
but if there is string with for example double dot or minus, like that: “0.5.1”, or “-24-.”

then it doesn’t work. So isn’t there any simply standard method to verify if String is a digit? Do I really need to write my own code for that?


This is probably the most similar way to do it to the code you posted. Note, don’t use operator[] to access the characters because it will be slow if your string is stored in utf8 internally.

bool is_number(const juce::String& s)
    auto t = s.getCharPointer();
    while (*t)
        if (! t.isDigit())
            return false;
    return true;


great. I still need to write some code to verify if there is only one dot, if it’s on the beginning or not, etc. But Ok I will do that :slight_smile:


Another approach is to use JUCE’s parser CharacterFunctions::readDoubleValue()

String text { "123.45,67" };

const auto charptr = text.getCharPointer();
auto ptr = charptr;

auto value = CharacterFunctions::readDoubleValue (ptr);

DBG ("Number: " << value << ((ptr - charptr == text.getNumBytesAsUTF8()) ? " ok" : " not ok"));

Explanation: the ptr is advanced through the string, so it will point either to the \0 or to the character, that doesn’t fit into the number. Hence the difference of the ptr to the initial charptr should be the length of the string, otherwise something went wrong…

String and Float