mrd
mrd

Reputation: 2183

Xml Serialize float value

Invoice invoice = new Invoice();
invoice.TotalInclTax = 4194.00f;
invoice.serialize();

I need some help in serializing float value. Currently it serializes 4194.00 as following:

<TotalInclTax>4194</TotalInclTax>

But, I want something like this:

<TotalInclTax>4194.00<TotalInclTax>

Upvotes: 2

Views: 3931

Answers (2)

Larry
Larry

Reputation: 18041

You can adapt your class a little to customize how TotalInclTax will be serialized :

static CultureInfo ci = CultureInfo.InvariantCulture;
float _TotalInclTax = 0;

[XmlIgnore]
public float TotalInclTax 
{
    get { return _TotalInclTax ; }
    set { _TotalInclTax  = value; }
}

[XmlElement("TotalInclTax")]
public string CustomTotalInclTax
{
    get { return TotalInclTax.ToString("#0.00", ci); }
    set { float.TryParse(value, NumberStyles.Float, ci, out _TotalInclTax); }
}

Upvotes: 5

Jim
Jim

Reputation: 21

There shouldn't be a problem if you use the deserialize methods to retrieve the value. It should put the decimal point and other digits if you try to serialize a value with non-zero values after the decmial point like 4672.34

But if for other reasons you absolutely need to control the decimal point formatting I would say serialize it as a string and use the string printing formatting for a float to set the string value and read the string value back into a variable of type float.

Upvotes: 1

Related Questions