-
decimal numbers
Hello,
I have a problem with an equation....
I divide a X number by 30.
This number X can be anything between 1 and 10 (ie 1,1.2,...)
I would like the result of this division to be formatted like this: xx.xx
Does anybody know how to do that ??
Thx
qali
-
No!
code:
function toDollar(num){
num = num * 100;
num = Math.round(num);
// you might want to use Math.floor if you don't want rounding
num = num / 100;
return num;
}
then use it as
code:
x = 1231231;
x = x / 30;
x = toDollar(x);
j
-
But that won't allways give 2 decimals, if that's what he's after.
Last edited by oldnewbie; 08-20-2003 at 12:49 AM.
-
No!
Originally posted by oldnewbie
But that won't allways give 2 decimals, if that what he's after.
then I request that the question be clarified. Does the number need to be in the format xx.xx where there are always four numbers and a decimal point? Do you want the number formatted so that it only goes to the second deciaml place? Or is it somewhere in between?
j
-
Re: decimal numbers
Originally posted by qali
...
I would like the result of this division to be formatted like this: xx.xx
...
Seems clear to me...
-
If it were the case...
Code:
Math.roundTo = function(num,dp){
var d = Math.pow(10,dp);
return Math.round(num*(d+0.00000001))/d;
};
stop();
//You can even use negative numbers for decimal places
//Math.roundTo(12345,-2)) //12300
//format a number into specified number of decimal places
Math.formatDecimals = function (num, digits) {
//if no decimal places needed, we're done
if (digits <= 0) {
return Math.round(num);
}
//round the number to specified decimal places
//e.g. 12.3456 to 3 digits (12.346) -> mult. by 1000, round, div. by 1000
var tenToPower = Math.pow(10, digits);
var cropped = String(Math.round(num * tenToPower) / tenToPower);
//add decimal point if missing
if (cropped.indexOf(".") == -1) {
cropped += ".0"; //e.g. 5 -> 5.0 (at least one zero is needed)
}
//finally, force correct number of zeroes; add some if necessary
var halves = cropped.split("."); //grab numbers to the right of the decimal
//compare digits in right half of string to digits wanted
var zerosNeeded = digits - halves[1].length; //number of zeros to add
for (var i=1; i <= zerosNeeded; i++) {
cropped += "0";
}
return(cropped);
} //Robert Penner May 2001 - source@robertpenner.com
my_num = 126.00156 / 30;
my_num2 = Math.formatDecimals(my_num,2);
trace (my_num2);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|