tags:

views:

101

answers:

5

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: 

1613841.93424 m = 1613,841.93424 km

Simply divide by 1000.

thelost
+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
round is not defined. Use Math.round.
Alsciende
Thank you, corrected
adam
+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
+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
Yeah, it's 1613, I was writing without thinking;)
Vafello
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
Funny how your function doesn't actually pads with zeros, but instead does the same thing as Number.toFixed :)
Alsciende
nice, thanks for this.
Vafello
@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