# Thread: Convert number to decimal

1. ## Convert number to decimal

Is there a JavaScript method to convert a "plain" number into a decimal one?
Say: 12345678 is converted to 12.345.678

2. That isn't a valid decimal...

Is there any pattern to your intent? Or you just want to move the decimal place from the back of the integer to somewhere inside or in front of the number?

3. Hi Smola,
There isn't a pattern to apply a regexp.
I need a generic method to make the conversion:

nnnnnnnnnnn... => n.nnn.nnn.nnn.nnn....

Edited: Well, it seems a pattern. Split from right to left step 3!

4. Presumably you are using the . as a thousands separateor but have confused everyone by referring to decimals (where presumably you use a comma but most people reading expect them the other way around).

5. ## [solved]

Originally Posted by felgall
...have confused everyone by referring to decimals...
Yes, my fault. Very sorry.
And confused the search engine also :-)
Stephen I know your work and I have already made a search for one of yours scripts at about.com - with the wrong keyword.

And as ever, your script works like a charm.

6. Well Maujor I don't think there is a single method for it but I went ahead and wrote a block of code that does the trick. You can even customize how many numbers you want between each decimal.

Code javascript:
```function reverseChars(theString) {		//reverse a string character by character
var revStr = "";
for(var i = theString.length - 1; i > -1; i--) {
revStr += theString.charAt(i);
};
return revStr;
};

function dot(reversedString, chunks) {  //chunks is how many #'s in between .'s
var dotStr = "";
for (var j = 0; j < reversedString.length; j++) {
if (j > 0 && j &#37; chunks == 0) {
dotStr += "."+ reversedString.charAt(j);
} else {
dotStr += reversedString.charAt(j);
};
};
return dotStr;
};

var num = 1234567890;
var numStr = num.toString();

s1 = reverseChars(numStr);	//reverse number
s2 = dot(s1,2);				//put decimals at desired intervals
result = reverseChars(s2);	//reverse it again

Now, your result is a string because no number has the format you wish. If you wanted to be bale to use each chunk of numbers then a different approach would need to be taken with arrays.

Hope this helps...

EDIT: Well fellas it looks like you made nice already. I didn't check for updates to the thread while I was toying with the solution above. It will still work with commas, just change the . to a , and voila!

7. Great Smola!
Your script works like a charm.
Now let's go to Firebug and check the run time (speed) for the two scripts.
Thanks a lot