input string was not in the correct format

J

Jeff

Hey

..NET 2.0

I'm parsing an XML file and read an attribute value out of a node. This
value ( value="0.0000") am I trying to convert to a decimal:

decimal _value = Convert.ToDecimal(reader.GetAttribute("value").ToString());

The code above gives this error:
"Input string was not in the correct format"

The regional settings is Norwegian on the computer I run this app on ...

In Norway comma are used instead of period to separate the decimals from a
number... like for example in US 0.0000 would in Norwegian become 0,0000

any suggestions on how to fix this?
 
J

Jon Skeet [C# MVP]

.NET 2.0

I'm parsing an XML file and read an attribute value out of a node. This
value ( value="0.0000") am I trying to convert to a decimal:

decimal _value = Convert.ToDecimal(reader.GetAttribute("value").ToString());

The code above gives this error:
"Input string was not in the correct format"

The regional settings is Norwegian on the computer I run this app on ...

In Norway comma are used instead of period to separate the decimals from a
number... like for example in US 0.0000 would in Norwegian become 0,0000

any suggestions on how to fix this?

Use Decimal.Parse, passing in CultureInfo.InvariantCulture, e.g.

decimal _value = decimal.Parse(reader.GetAttribute("value"),
CultureInfo.InvariantCulture);

Jon
 
M

Marc Gravell

Not tested, but perhaps:
reader.MoveToAttribute("value");
reader.ReadContentAsDecimal();

Marc
 
M

Mihai N.

I'm parsing an XML file and read an attribute value out of a node. This
value ( value="0.0000") am I trying to convert to a decimal: ....
any suggestions on how to fix this?

Jon is right, CultureInfo.InvariantCulture is the solution in this case.
Because the thing is in an XML, it should be locale-independent.
So make sure to always use CultureInfo.InvariantCulture, both to
create the XML and to read it.
And you have to do the same not only for numbers, but also for dates and
times (and convert them to UTC times), if you have any such data.
 
M

Marc Gravell

Actually, just glancing through the object library - there is a
wrapper that encapsulates all the xml rules for the different types
(it is used internally by XmlReader) - XmlConvert.

i.e.

decimal _value = XmlConvert.ToDecimal(reader.GetAttribute("value"));

Not only does this make it clear that you are talking about xml
formats (and apply the correct rules automatically), but it works for
those types that aren't stored verbatim - for instance it looks like
TimeSpan has a non-trivial implementation.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top