ColdFusion - 以磅为单位将重量转换为磅和盎司

时间:2011-08-19 16:57:17

标签: coldfusion

我正在写一篇ColdFusion CFSCRIPT中的转换文章。

我需要将重量换算成磅和盎司。

所以,3.1565需要变成3磅和3盎司。 1.512将变为1磅和9盎司(围绕盎司) 0.25将变为0磅和4盎司。

我的想法是以磅的总重量乘以十六,这将给我总盎司。然后我需要通过除以十六来提取均匀的磅数,其余的将是盎司。我真的不知道如何准确地使用有效的代码。

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

// REMAINDER IS OUNCES - ROUND UP 


}
</cfscript>

4 个答案:

答案 0 :(得分:3)

像这样(没有经过广泛测试)。

编辑:如果输入可能为负数,请使用abs()值进行计算

<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>

答案 1 :(得分:1)

整数除法和模数应该为您提供所需的值。

<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>

答案 2 :(得分:0)

这应该这样做:

<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>

答案 3 :(得分:0)

你几乎拥有你需要的东西。要提取磅数,除以16.余数(“mod”)是盎司。

<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>
相关问题