尝试计算框的分数时的十进制精度损失

los*_*wpf 3 c# algorithm decimal rounding

我有一个场景,我有一个包含3罐的标准盒子.出于显示和查询的目的,我必须根据其标准配置的十进制数量进行报告.不可能说1盒3罐,1盒2罐......等等

例如,最初我将具有 的3罐1盒
然后我除去1种可导致 0.66的重复的3罐箱
然后我删除1以上即可,导致 0.33的重复的3罐箱
然后我除去,以生成最终罐0.0000000000000000000000000001的框3罐

当我删除最终的罐头时,我希望该值为0盒3罐,因为现在每个罐子都已从原始盒子中移除.我很欣赏由于在处理有限数量的位时无法表示0.33重复这一事实而导致精度损失.

问题:对于那些需要使用舍入(可能是财务)的系统有更多经验的人,我有哪些选择来解决这个问题?如何删除最后一个可能意味着该框不再存在?

编辑:
最后.我用洛伦Pechtel建议和存储罐的数量然后当我需要证明我有多少标准盒将罐的总人数的罐头标准箱仍然给出了一个递归结果的数量,但是这是罚款报告事情的一面.

以下是一些代码,我希望这些代码可以帮助更多地概述问题: -

     static void Main(string[] args)
     {
        var box = new StandardBox(3);
        var boxDetail = new BoxDetail(1.0m, box);

        var allBoxes = new AllBoxes();
        allBoxes.AddBox(boxDetail);
        allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
        Console.WriteLine(allBoxes);
        allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
        Console.WriteLine(allBoxes);
        allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
        Console.WriteLine(allBoxes);
        Console.ReadLine();
    }
}

public class StandardBox
{
    private decimal _quantity;
    public StandardBox(decimal quantity){_quantity = quantity;}
    public decimal Quantity {get { return _quantity; }}
}

public class BoxDetail
{
    private decimal _quantity;
    private StandardBox _box;

    public BoxDetail(decimal quantity, StandardBox box)
    {
        _quantity = quantity;
        _box = box;
    }

    public void RemoveItem(decimal quantity)
    {
        var newQuantity = quantity / _box.Quantity;
        _quantity = _quantity - newQuantity;
    }

    public override string ToString()
    {
        return _quantity.ToString() + " of " + _box.Quantity.ToString();
    }
}

public class AllBoxes
{
    private List<BoxDetail> allBoxes = new List<BoxDetail>();

    public AllBoxes(){}

    public void AddBox(BoxDetail box){allBoxes.Add(box);}

    public void RemoveItemFromBox(BoxDetail box, decimal quantity)
    {
        var boxDetailLineToModify = allBoxes.Find(b => b.Equals(box));
        boxDetailLineToModify.RemoveItem(quantity);
    }

    public override string ToString()
    {
        var results = string.Empty;
        foreach (var box in allBoxes)
        {
            results += box.ToString() + "\n";
        }
        return results;
    } 
}
Run Code Online (Sandbox Code Playgroud)

Lor*_*tel 7

我解决这些问题的方法是不要这样做.

当它是财务资料时尤其如此.

财务方面通常很容易处理 - 用便士做所有工作,而不是美元.

我对你的问题的第一反应是储存罐而不是罐子.