How to convert XML field to decimal

Asked

Viewed 92 times

0

When reading an Nfe XML I read fields that in my system are decimal, for example qCom (Quantity), vUnCom (Unit Value) and vProd (Product Value), but the XML file uses the point as decimal separator, then when making a simple conversion the value is completely wrong, for example:

inserir a descrição da imagem aqui

Note that in the file is 80.0000 and converting is 800000, I found some options on the internet, however they did not work, as force the Cultureinfo informing the score, but it does not seem to me that, I tried to use Decimal.Parse() etc... I have no idea what it might be, someone like you has been there?

  • 1

    ps does not make a replace semicolon?

  • Because I do not know what would be the behavior if the value is for example 6.342,33, if I receive in XML 6342.33 there would be possible, I did not test this possibility.

  • 1

    I do not believe that the NF is so "default" so, every hour comes a format. In the documentation does not speak the standard format that data are sent?

  • Was able to verify the answer?

  • Yes, I followed the idea of even converting and doing replace. Thank you

1 answer

2

As stated in microsoft documentation, when receiving a string, you can convert it to the various numeric types with the methods Parse or TryParse The difference between the two methods is the ease of not having to worry about exceptions when using the TryParse.

In your specific case could be used the Decimal.Tryparse, more specifically Overload TryParse(String, NumberStyles, IFormatProvider, Decimal). Because it is a TryParse, there is always the return booleano indicating whether it was possible to convert to string passed according to the given parameters. In this Overload you can pass

  • to string which will be converted (parameter s),
  • one System.Globalization.NumberStyles (parameter style), where you can define number formatting styles (in your case, you could use the Number or Float, for example),
  • one IFormatProvider (parameter provider), where the representation details of your number can be specified,
  • one decimal, which will contain the number if conversion is possible (parameter out result).

The provider (one IFormatProvider) can be both a CultureInfo, can use CultureInfo.InvariantCulture or specify en-US, according to the example presented, or a NumberFormatInfo, where it is possible to detail the format of the string incoming (ex: #,##0.000).

A functional example of the presented can be found in https://dotnetfiddle.net/kAo4v2.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.