开发者

ColdFusion - Converting weight in pounds to pounds and ounces

I am writing a little conversion piece in ColdFusion CFSCRIPT.

I need to convert a weight in pounds to pounds and ounces.

So, 3.1565 needs to become 3 pounds and 3 ounces. 1.512 will become 1 pound and 9 ounces (round up the ounces).

0.25 will become 0 pounds and 4 ounces.

My thought is to take the total weight in pounds and multiply it by sixteen, which will give me the total ounces. Then I'll need to extract the even pounds by dividing by sixteen and the remainder will be the ounces. I really don't know ho开发者_如何转开发w to do this accurately and with efficient code.

<cfscript>
MyPounds = 0;
MyOunces = 0;
ThisPounds = 2.12345;
MyOunces = (ThisPounds * 16);
// EXTRACT THE NUMBER OF POUNDS

// REMAINDER IS OUNCES - ROUND UP 


}
</cfscript>


Something like this (not extensively tested).

EDIT: If the input can be negative, use the abs() value for calculations

<cfset theInput  = 0.25>
<!--- round down to get total pounds --->
<cfset lbs       = int(theInput)>
<!--- extract remainder. multiply by 16 and round up --->
<cfset ounces    = ceiling((theInput - lbs)  * 16)>
<cfoutput>#lbs# pounds #ounces# ounces</cfoutput>


Integer division and Modulus should give you the values you need.

<cfscript>
MyPounds = 0;
MyOunces = 0;
ThisPounds = 2.12345;
MyOunces = (ThisPounds * 16);
// EXTRACT THE NUMBER OF POUNDS
weightInPounds = MyOunces \ 16;
// REMAINDER IS OUNCES - ROUND UP 
remainderOunces = ceiling(MyOunces MOD 16);
</cfscript>


This should do it:

<cffunction name="PoundConverter" returntype="string">
    <cfargument name="Pounds" type="numeric" required="true" hint="" />
    <cfset var TotalPounds = Fix(Arguments.Pounds) />
    <cfset var TotalOunces = Ceiling((Arguments.Pounds - TotalPounds) * 16) />
    <cfreturn TotalPounds & " pounds and " & TotalOunces & " ounces" />
</cffunction>


<cfoutput>
    #PoundConverter(3.1565)#<br />
    #PoundConverter(1.512)#
</cfoutput>


You pretty much have what you need. To extract the number of pounds, divide by 16. The remainder (the "mod") is the ounces.

<cfscript>
    function poundsandounces( initvalue ) {
        var rawvalue = val( initvalue ) * 16;
        var lbs = int( rawvalue / 16 );
        var oz = ceiling( rawvalue % 16 );
        return "#lbs# pounds #oz# ounces";
    }
</cfscript>

<cfoutput>#poundsandounces( 0.25 )#</cfoutput>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜