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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Length of a number in javascript. 4

Status
Not open for further replies.

borntorun

MIS
Oct 16, 2003
82
GB
Hi,

I need to test if a number has a decimal point and count the characters before the decimal point. Obviously without a decimal point i can just do length.

Thanks.
 
myString.indexOf(characterOrStringOfInterest)

...will return the 0-based index of the start of the parameter in the string. If it is not present at all, it returns -1.

If it's not -1, then you can use the substring function, setting the first parameter to 0 (start of the string) and the second/last parameter to the index of the decimal you've found.

Is that enough to go on?

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Cory,

I think you woke up outside the box this morning! :)

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
This is pretty much the same as cLFlaVA's, but using the toString method inherent to all Number objects:

Code:
var someNum = 123;
alert(someNum.toString().split('.')[0].length);
someNum = 12345.67
alert(someNum.toString().split('.')[0].length);

Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I must be outside the box too because that's pretty much what I would have typed up too [smile]

-kaht

<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>
 
I guess your solutions are better because they don't require testing for the existence of the decimal first. I see...

[yoda voice]Wise beyond your years, you are.[/yoda voice]

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
yeah man, last night's dinner was terrible. i was definitely forced to sleep outside the box, therefore, that's where i woke up.



*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
Would you settle for David Hasselhoff?


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
I don't have sound on my computer at work, but I am laughing just the same!

[rofl]


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Aw man, you guys missed the other way:
Code:
var someNum = 123.456
alert((Math.floor(someNum)).toString().length);

And some recursion is great for the diet :) :
Code:
function intCount(aNum){
   return (abs(aNum) >= 1)?1 + intCount(aNum/10):0;
}

barcode_1.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top