2014-01-14 58 views
0

例如說是轉換碼在JS英里的功能是:計算一個浮點數的剩餘部分並使用javascript轉換?

function yards_2_miles(num) 
{ 
    return num *= 0.000568182; 
} 

,我們要轉換3000碼:

var a = yards_to_miles(3000); // gives us 1.70455 miles 

現在我的問題是小數點後計算的一切(餘數),看它是否等於在碼整數,在僞

if the remainder equals a whole number 
    alert("1 mile 200 yards); 
else 
    alert(3.2 miles); 

林不知道如果這是混亂的,但我不擅長與馬部份。

回答

2

遺留碼的數量是模量,通過

yards % 1760 

給出雖然整體的里程數是通過(在一英里碼)除以碼,作爲一個整數:

parseInt(yards/1760) 

所以,你可以寫你的功能

function yards_2_miles(num) 
{ 
    var miles = parseInt(num/1760); 
    var yards = num % 1760; 
    return miles + " miles and " + yards + " yards"; 
} 

Working example on jsfiddle

0
var miles = Math.floor(a); 
var dec = a - miles; 
var yards = dec/.000568182; 
if(yards == Math.floor(yards) 
    alert(miles + "miles " + yards + " yards"); 
else 
    alert(a + " miles"); 

編輯:在這裏,一個更強大的解決方案我原來的答覆結合了亞當的

function show_yards_to_miles(yards) { 
    miles = Math.floor(yards/1760); 
    rem = yards % 1760; 
    if(rem == Math.floor(rem)) 
     alert(miles + " miles " + rem + " yards"); 
    else 
     alert(yards/1760 + " miles"); 
} 
+0

繼承人的jsfiddle:http://jsfiddle.net/pSc27/1/ –

+0

@TomHeard謝謝 – acbabis

+0

我不認爲這是行得通的 - 如果我把3211放在jsfiddle中,我會得到'1.824432402英里' –