Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I check the number of digits after a decimal?

Status
Not open for further replies.

JohnnyBGoode

Programmer
May 1, 2002
76
CA
I have a string:

var temp;
temp = '1000.123';

I need to know how many decimal places there are. Is there an easy way? The answer is gonna be 3...obviously.
 
sure:

var temp;
temp = '1000.123';

var numDec = temp.split(".")[1].length;

=========================================================
if (!succeed) try();
-jeff
 
Or:

var number='1000.123';
var decpoint= (number.length-1)-number.indexOf('.');
 
How does the Split function work?
text.split(".")[1].length;
is it spliting based on a ".", and then counting the length of the second element of the array? What if a value of "100.34.34" was passed in? Can this function be used to determine the number of decimals in a string? The example i gave has 3 decimals. Obviously, this is not permitted.
 
JohnnyBGoode,

"is it spliting based on a ".", and then counting the length of the second element of the array?" EXACTLY.

as for your second question, I would use some sort of validation routine to disallow more than one decimal, perhaps:
[tt]
var count = 0;
for (ndx = 0; ndx < text.length; ndx++)
if (text.charAt(ndx) == &quot;.&quot;) count++;
if (count > 1) {
alert(&quot;Invalid number of decimals.&quot;);
return false;
}
[/tt]
=========================================================
if (!succeed) try();
-jeff
 
You can also use:

if (isNaN(text)) return false;

since the isNan() function will return true if there's more than one decimal point in the string (or any other non-numeric character). Or you can use:

if (text.indexOf('.') != text.lastIndexOf('.')) return false;

All 3 of the methods listed here and in jemminger's post should work equally well, just taking a different approach to the same problem. :)#
 
Thank you all for your assistance. The isNaN works and is the simplest way. I didn't realize that the isNaN returned false for multiple decimals. Thanx again.
 
cool - i'm always wondering about other solutions to the same problems, and trollacious always comes up with good ideas. i felt there had to be a more efficient way to do this.
=========================================================
if (!succeed) try();
-jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top