javascriptdata-conversionunits-of-measurement

function for converting kilograms to pounds and ounces


I'd like to convert kilos into pounds and ounces e.g. if a user enters 10 kg then the function should return 22 lb and 0.73 oz

Any ideas?


Solution

  • Based on @dlamblin's answer, here's a function that returns the pounds and ounces in a structure.

    function kToLbs(pK) {
        var nearExact = pK/0.45359237;
        var lbs = Math.floor(nearExact);
        var oz = (nearExact - lbs) * 16;
        return {
            pounds: lbs,
            ounces: oz
        };
    }
    
    var imperial = kToLbs(10);
    alert("10 kg = " + imperial.pounds + " lbs and " + imperial.ounces + " oz.");
    

    Here's how you would go the other way:

    function lbsAndOzToK(imperial) {
        var pounds = imperial.pounds + imperial.ounces / 16;
        return pounds * 0.45359237;
    }
    
    var kg = lbsToK({ pounds: 10, ounces: 8 });
    alert("10 lbs and 8 oz = " + kg + " kg.");