10
Is there any way to know if a number is decimal, ie if it contains "comma"?;
One code I found was this:
Html
<input type="text" onblur="isNumber(this.value)" id="text" />
Javascript
function isNumber(text){
valor = parseFloat(text);
if ((!isNaN(valor))==false){
alert("Por favor, não digite ...");}
return true;
}
Via: http://scriptsexemplos.blogspot.com.br/2011/04/validar-se-um-numero-e-decimal.html
But it’s not working. To see how was click here
To summarize, I just want a condition that returns
true
for: 5.69541
and
false
for: 569
.
Thank you.
Your last line of code solves the whole problem in a more elegant way than my solution.
– bfavaretto
One thing I never understood until today are these mixed symbols (
/^-?\d+\.\d+$/
), that you called regex. I will search and understand your reply @mgibsonbr. But it sounds great.– Samir Braga
@Samirbraga Even search, because regular expressions (regular Expressions -
RegExp
or simply regex) are a powerful yet often misused tool. My expression above says:^
string start,-?
with or without less at the front,\d+
one or more digits,\.
dot,\d+
one or more digits,$
end of string.– mgibsonbr
And another, your regex solution is much faster than mine: http://jsperf.com/regex-versus-parseint-float-isnan. @Samirbraga, you should accept this answer instead of mine...
– bfavaretto
@bfavaretto No V8 (Chrome, Opera), yes, but in Firefox and Safari yours is faster. Regex is not usually something efficient... But in that case, it is necessary (the
parseFloat
suffers from the numeric prefix problem and any suffix, as mentioned in the answer).– mgibsonbr
I like the solution with regex because it’s much simpler. I needed the
isNaN
to eliminate the suffixes parseint/float passes, and other non-numerical values.– bfavaretto