在构建会计系统时,我遇到了一个大问题。假设我开了一张发票,然后,我必须申请与负值相同金额的信用,我有时会遇到 1 美分的舍入问题。
我的问题仅与负值有关!
让我们看看这个测试特定正负值的脚本。出于调试目的,我还发送了参数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
我真的被困在这里,希望能得到一些帮助。非常感谢!!