计算浮点数的余数并使用javascript进行转换?

时间:2014-01-14 19:50:13

标签: javascript decimal

比如说一个在js中将码数转换为英里的函数是:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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");
}