View Full Version : format number

esthera

12-27-2004, 07:45 AM

I have the following function

function custRound(x,places) {

return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)

}

Can someone help edit this that it should always return a number with 2 decimal points. (.3 should become .30) and if possible put the , in where it belongs.

Philip M

12-27-2004, 09:08 AM

This is another topic which has been dealt with many times before and would have been answered by the Search tool.

<script type="text/javascript">

function formatNumber(x){

return x.toFixed(2).toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');

}

alert(formatNumber(1234567.8976));

</script>

Another easy way is to use

Math.round(100*x)/100

joh6nn

12-27-2004, 09:44 AM

i wasn't sure if you wanted code, or help, so i figured i'd give help first, and then give code if you asked for it.

here (http://www.codingforums.com/showthread.php?s=&threadid=13577) is a link to a contest we had a long while back about formatting numbers to look like currency. i liked a lot of the other entries better than mine, though my entry is there too.

the first step to modifying code is to understand what the code you already have does. so, because programming languages owe almost everything to math, we're gonna follow some math rules, and work from the inside of the parentheses out. the farthest in you get is to use the Math.pow() method to raise 10 to the power of places, which you want always to be 2, so that's 10 squared, or 100. so you can replace all of that Math.pow() nonsense with 100. so you end up with (Math.round(x*100))/100 . which is a lot simpler to understand, i think.

you want to make sure to do your rounding before you try to group your number with the comma, because the rounding method will negate all the work you do with grouping and padding. that probably doesn't make a whole lot of sense now, but if you ever pad and group first, and then round, then you'll see what i'm talking about. (you might want to try padding around grouping first, just for the hell of it, so you can see what i mean).

grouping is pretty easy: you convert your number to a string, and then count from the end of the string, to the beginning. every 3rd place, you put in a comma. try taking a look at code to make a string backward; that should help.

to pad a number with 0s, you compare its length (again, it has be converted to a string) with the number of decimal places you want. just run through a for-loop until your number's length is the same as the number of 0s you want.

hope that's been helpful.

Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.