在建立會計系統時,我遇到了一個主要問題。比方說,我開發票,然後,我必須申請一個相同金額的信用作爲負值,我有時舍入問題1分。AS3中貨幣四捨五入的不一致
我的問題是關於負值只!
讓我們來看看這個腳本是測試一個特定的正面和負面的價值。爲了調試目的,我還發送參數expectedResult;
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="creationCompleteHandler()">
<fx:Script>
<![CDATA[
import mx.formatters.CurrencyFormatter;
import mx.formatters.NumberBaseRoundType;
private function roundDecimal(num:Number, expectedResult:Number):void
{
var rnd:CurrencyFormatter = new CurrencyFormatter();
rnd.precision = 2;
rnd.useThousandsSeparator = false;
rnd.currencySymbol = '';
if (num >= 0)
rnd.rounding = NumberBaseRoundType.NEAREST;
else
rnd.rounding = NumberBaseRoundType.DOWN; // The problem is here, ALWAYS!
var result:Number = Number(rnd.format(num));
if (result != expectedResult)
trace("Error : " + result + " (Expecting " + expectedResult + ")");
else
trace("OK : " + result);
}
protected function creationCompleteHandler():void
{
var num:Number;
var expectedResult:Number;
// Test number 1
num = 5.653;
expectedResult = 5.65;
roundDecimal(num, expectedResult);
roundDecimal(-(num), -(expectedResult));
trace("------------");
// Test number 2
num = 5.655;
expectedResult = 5.66;
roundDecimal(num, expectedResult);
roundDecimal(-(num), -(expectedResult));
trace("------------");
// Test number 3
num = 5.657;
expectedResult = 5.66;
roundDecimal(num, expectedResult);
roundDecimal(-(num), -(expectedResult));
}
]]>
</fx:Script>
</s:WindowedApplication>
當然,我試圖修改負值的舍入類型,但沒有成功..
看一看不同的舍入類型及其結果:
//////////// Test 1 ////////////
if (num >= 0)
rnd.rounding = NumberBaseRoundType.NEAREST;
else
rnd.rounding = NumberBaseRoundType.DOWN; // The problem is here, ALWAYS!
OK : 5.65
Error : -5.66 (Expecting -5.65)
------------
OK : 5.66
OK : -5.66
------------
OK : 5.66
OK : -5.66
//////////// Test 2 ////////////
if (num >= 0)
rnd.rounding = NumberBaseRoundType.NEAREST;
else
rnd.rounding = NumberBaseRoundType.UP;
OK : 5.65
OK : -5.65
------------
OK : 5.66
Error : -5.65 (Expecting -5.66)
------------
OK : 5.66
Error : -5.65 (Expecting -5.66)
//////////// Test 3 ////////////
if (num >= 0)
rnd.rounding = NumberBaseRoundType.NEAREST;
else
rnd.rounding = NumberBaseRoundType.NEAREST; // The problem is here, ALWAYS!
OK : 5.65
OK : -5.65
------------
OK : 5.66
Error : -5.65 (Expecting -5.66)
------------
OK : 5.66
OK : -5.66
我真的卡在這裏,並會感謝一些幫助.. 非常感謝!
來吧它的一行代碼。 trace(num> = 0?(Math.round(num * 100)/ 100):-(Math.round(-num * 100)/ 100)) –