开发者

Unit conversion in Javascript

I have a question concern开发者_C百科ing 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.


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)


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)


1613841.93424 m = 1613,841.93424 km

Simply divide by 1000.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜