Arh! I’ve forgotten how to make decimal variables fixed.
I’m making a small game with a timer that have to show the time in seconds with 2 decimals all the time (i.e. 34.71 sec. or 51.00 sec.)
How do I force the time-variable to always have two decimals?
If you had searched you’d have found you answer in no time.
http://www.kirupaforum.com/forums/showthread.php?s=&threadid=43439&
The only way I know is this:
Let’s say your un-trimmed variable is 123456789. What you do is you multiply it with 0.00001 so that you get 1234.56789.
Then you use Math.round() on the var so the result will be 1235. Then you multiply it with 0.01, returning 12.35.
[AS]
yourVar = 123456789;
yourVar *= 0.00001; //returns 1234.56789
yourVar = Math.round(yourVar); // returns 1235
yourVar *= 0.01
trace(yourVar); // returns 12.35
[/AS]
well the problem with that is if it’s 1200, and if u mulitply it by 0.01 u’ll get 12 and not 12.00.
Originally posted by davidchang
well the problem with that is if it’s 1200, and if u mulitply it by 0.01 u’ll get 12 and not 12.00.
You can always convert the number into a string and add some formatting to it.
function getSeconds(ms) {
var s = String(Math.round((ms/1000)*100)/100);
var n = (s.indexOf(".")<0 ? s+"." : s).split(".");
while (n[1].length<2) n[1] = n[1]+"0";
return n[0]+"."+n[1];
}
trace(getSeconds(0)); //0.00
trace(getSeconds(10000)); //10.00
trace(getSeconds(10007)); //10.01
trace(getSeconds(10070)); //10.07
trace(getSeconds(10700)); //10.70
[AS]function decimal(number, decimalPlace){
var t = “” + Math.round(number * Math.pow(10, decimalPlace)) / Math.pow(10, decimalPlace);
if (t.indexOf(".") == -1) {
t += ".";
}
while(t.length - t.indexOf(".") <= decimalPlace) {
t += "0";
}
//Note: the output will be a String and not a numerical value.
return t;
}[/AS]