从模型中获取一定的小数

时间:2012-05-16 17:00:53

标签: c# model

我正在创建一个模型,我希望所有的十进制值最终都是2位小数(货币)。这就是我的想法,但显然不起作用。

public class Fees
{
    public decimal permitFee { set; get { return Math.Round(permitFee, 2); } }
    public decimal planReviewFee { set; get { return Math.Round(planReviewFee, 2); } }
    public decimal surchargeFee { set; get { return Math.Round(surchargeFee, 2); } }
    public decimal totalFee { get { return permitFee + planReviewFee + surchargeFee; } }
}

我应该如何设置我的对象以获得正确的输出值?

3 个答案:

答案 0 :(得分:4)

我不相信你可以使用这样的属性(返回自己)。尝试使用该属性的基础变量,看看是否能解决您的问题。

Stack overflow error in C# set/get

答案 1 :(得分:1)

请参阅上面的评论并考虑将值存储为整数

public class Fees {  

private int permit;  
private int planReview;  
private int surcharge;  
public decimal permitFee { set { permit = (int) (value * 100); }; 
                           get { return permit / 100; } }  
public decimal planReviewFee { set { planReview = (int) (value * 100); } 
                               get { return planReview / 100; } }
public decimal surchargeFee { set { surcharge = (int) (value * 100); } 
                              get { return surcharge / 100; } }
public decimal totalFee { get { return permitFee + planReviewFee + surchargeFee; } }  }  }

答案 2 :(得分:0)

以下是我最终采取@ tom_yes_tom的建议。

public class Fees
{
    private decimal permit;
    private decimal planReview;
    private decimal surcharge;

    public decimal permitFee
    {
        set { permit = Math.Round(value, 2); }
        get { return permit; }
    }
    public decimal planReviewFee 
    {
        set { planReview = Math.Round(value, 2); }
        get { return planReview; } 
    }
    public decimal surchargeFee 
    {
        set { surcharge = Math.Round(value, 2); }
        get { return surcharge; } 
    }
    public decimal totalFee 
    { 
        get { return permitFee + planReviewFee + surchargeFee; } 
    }
}