# Determine a string value is numeric?

Is their any simple function available in Juce that can determine whether a String variable holding
is numeric value or not?

If you can give me a simple definition of “numeric”, I’ll give you a simple function to determine it!

By numeric, I mean a string value only with numbers.
e.g: String strValue holds “123” (this value may read from a file). In a later stage i want to cast this into int/double.
Before that i need to check the string is numeric only(not alphanumeric like Ab123X)
Is there any function for this check?

u can write function like below for checking that.

[code]bool IsStringOnlyNumeric( const juce::String str )
{
juce::String numericStr( str.getIntValue() );

``````if ( str.length() == numericStr.length() )
{
return true;
}
return false;
``````

}
[/code]

Hmm… Sorry, that’s not a great suggestion! Lots of ways it could give the wrong answer, as well as being very inefficient!

If you really just wanted to know if it contains only digits, you’d say

But you need to think it through - what about spaces, or negative numbers, or strings that are numeric but out-of-range, etc. etc.

If you’re after an integer, a simple trick would be

Which isn’t perfect, but would work except for weird edge cases like “-0”. It’d also be mean that you’d only have to do the int conversion once, and in the case of non-zero values the check would require no extra work at all.

My code will work fine… She just wanted the integer number. so the the (.) dot is not significant for us now. Moreover my code will perfectly fine for negative numbers too. I dont find any fault in that. Please give ur condition where it will fail.

[attachment=0]hmmmmm.jpg[/attachment]

" 123"
"123 “
“00"
“x”
”-0"
”+1"
"0123"
“123foo”
“1234567890123456789”
…etc…

Those are just the ones that sprung to mind immediately. I could probably find plenty more edge cases given a minute or two to think about it.

Yeah thats wat i had written code… If the string has ant other charecters other than “±0987654321” it will fail. The person dint wanted the string other than these characters. Even the placement of ‘+’ and ‘-’ matters over here. the only case it fails is for leading zero strings. like “0023” and “-023”.

Weirdly enough, I actually now require this in an app it building and just stumbled across this thread. Has anyone written anything in the last ~9 years to do this?

Something like this? https://gcc.godbolt.org/z/GEPvn_ Can be used at compile-time or runtime!