Reputation: 4061
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.
Upvotes: 3
Views: 33788
Reputation: 9323
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
Upvotes: 1
Reputation: 28795
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
Upvotes: 1
Reputation: 344301
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)
Upvotes: 33
Reputation: 9759
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)
Upvotes: 3