xml序列化的double

时间:2012-07-24 14:09:11

标签: c# xml-serialization

当我序列化我的对象时,我的双值打印为-9.9999999999988987E-05 我怎么能解决这个问题所以我可以得到一个带小数点后4位的数字?

public class DecisionBar
    {
    public DateTime bartime 
         { get; set; }
    public string frequency
             { get; set; }
    public bool HH7
            {get;set;}
    public bool crossover
            {get;set;}
    public double mfe
            {get;set;}
        public double mae
            {get;set;}
                public double currentprofitability
            {get;set;}
    public double entryPointLong
            {get;set;}
    public double entryPointShort
            {get;set;}
    public double exitStopFull
            {get;set;}
    public double exitStopPartial 
                {get;set;}
     [XmlAttribute]         
    public string EntryOrExit
                {get;set;}
//    public DecisionBar()
//          {
//          crossover =false;
//          }

    }

输出

<DecisionBar>
    <bartime>2012-07-24T08:59:00</bartime>
    <frequency>1 MINUTES</frequency>
    <HH7>false</HH7>
    <crossover>false</crossover>
    <mfe>0.00019999999999997797</mfe>
    <mae>-9.9999999999988987E-05</mae>
    <currentprofitability>0</currentprofitability>
    <entryPointLong>0</entryPointLong>
    <entryPointShort>0</entryPointShort>
    <exitStopFull>0</exitStopFull>
    <exitStopPartial>0</exitStopPartial>
</DecisionBar>

3 个答案:

答案 0 :(得分:3)

get中的舍入值,因此在序列化序列化程序期间读取舍入值。

double _mfe;
double _mae;
        public double mfe
        {
             get
             {
                return Math.Round((decimal)_mfe, 4, MidpointRounding.AwayFromZero)
             }
             set
             {
                 _mfe = value;
             }
        }

        public double mae
        {
             get
             {
                return Math.Round((decimal)_mae, 4, MidpointRounding.AwayFromZero)
             }
             set
             {
                 _mae= value;
             }
        }

答案 1 :(得分:2)

您可以在使用

序列化前对其进行舍入
mfe = Math.Round(mfe, 4, MidpointRounding.AwayFromZero) 

要自动执行此操作,您可以使用[XmlIgnore]属性标记实际属性,并创建返回舍入值的新属性。

我建议不要使用私有字段和get; set;访问器,因为getter每次都会对属性进行舍入,而不是仅在序列化时使用。

答案 2 :(得分:0)

您可以将双精度格式化为4位小数

double number = 123.64612312313;
number = double.Parse(number.ToString("####0.0000"));