I have a question concerning number conversion i JS. I have a number like 1613841.93424 (meters) and I would like it to convert to 1.6 km instead. What JS function should I use for that? Thanks.
+1
A:
Use Math.round:
m = 1613841.93424;
var km = Math.round(m / 100) / 10;
// km = 1613.8
This will give a result rounded to 1/10th km
adam
2010-03-18 16:02:33
round is not defined. Use Math.round.
Alsciende
2010-03-18 16:04:43
Thank you, corrected
adam
2010-03-18 16:11:56
+3
A:
To display with one number to the right of the decimal (if that is what you're asking..I'm guessing you know how to convert m to km) :
.toFixed(1)
kekekela
2010-03-18 16:04:13
+3
A:
To convert from metres to kilometres, simply divide by 1000. To format a number using fixed-point notation, you can use the toFixed() method:
var km = 1613841.93424 / 1000;
alert(km.toFixed(1) + " km"); // 1613.8 km
Note: 1613841.93424 meters != 1.6 km (Source)
Daniel Vassallo
2010-03-18 16:04:36
A:
i usually deal with float padding numbers with a function of my own
var zeroPad = function(num, pad){
var pd = Math.pow(10,pad);
return Math.floor(num*pd)/pd;
}
alert(zeroPad(1.32878,3)); // outputs 1,328
alert(zeroPad(1.32878,1)); // outputs 1,3
Then finally to convert to kms divide by 1000, apply zeroPad and solved
example :
var m = 1613841.93424; var km = zeroPad(m/1000,3); alert(km); // outputs 1613.841
markcial
2010-03-18 16:12:17
Funny how your function doesn't actually pads with zeros, but instead does the same thing as Number.toFixed :)
Alsciende
2010-03-18 16:16:09
@Alsciende its true, i tried right now, i will remember that next time, surely i have a lot of functions in my code that can be solved with native code, but im still learning
markcial
2010-03-18 17:07:54