简体   繁体   中英

calculating the remainder of a float and converting using javascript?

Say for instance a function that converts yards to miles in js is:

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

and we want to convert 3000 yards:

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

Now my problem is to calculate everything after the decimal point(remainder) to see if it amounts to a whole number in yards, in pseudo

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

Im not sure if this is confusing, but i'm not good with maths.

The number of yards left over is the modulus , given by

yards % 1760

While the number of whole miles is the yards divided by (yards in a mile), as an integer:

parseInt(yards / 1760)

So you can write your function as

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

Working example on jsfiddle

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");

EDIT : Here, a more robust solution combines my original answer with adam's

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM