Skip to content
Advertisement

check if number string contains decimal?

After doing a sqrt()

How can I be check to see if the result contains only whole numbers or not?

I was thinking Regex to check for a decimal – if it contains a decimal, that means it didn’t root evenly into whole numbers. Which would be enough info for me.

but this code isnt working…

result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result)); 

I bet there’s other ways to accomplish the same thing though.

Advertisement

Answer

. means any char. You have to quote the dot. “.”

Or you could test

if (result > Math.floor(result)) {
   // not an decimal
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement