gog
gog

Reputation: 12988

How to deal with right zeros in a string to decimal conversion?

in my website i need to read data from a XML, and some of these datas are decimal values. Sometimes the value comes correct: 1 or 72,59and sometimes the value comes like 1.0000 or 72,590000, how is the best way to convert it to the right format:

ps: I need a string value.

Thanks!

Upvotes: 0

Views: 128

Answers (3)

phoog
phoog

Reputation: 43056

You write that you tried

string.Format("{0:F}","1.00000");

The problem with this is that you're passing a string into the function. Numeric formatting only works on numeric data types. Convert the value to a decimal first and then format it.

Try this

public string ReformatDecimalString(string input)
{
    const string formatString = //something
    var decimalValue = decimal.Parse(input);
    return decimalValue.ToString(formatString);
}

When you are formatting a single numeric value, it's slightly more efficient to use x.ToString(formatString) than string.Format(formatString, x). But note that the specific format string will be different in the two cases.

If your input data has decimal points (not commas) and your computer's culture uses decimal commas, you ought to be able to parse the value correctly by using CultureInfo.InvariantCulture:

var decimalValue = decimal.Parse(input, CultureInfo.InvariantCulture);

Upvotes: 1

RyanTimmons91
RyanTimmons91

Reputation: 460

If I'm reading your answer correctly, you're trying to convert Integer values you pull from an XML file into string values without trailing zeroes ("ps: I need a string value.")

this code:

decimal test = 20.000000m
test.ToString("G29");

might do what you want

Upvotes: 0

GEEF
GEEF

Reputation: 1185

What format are you wanting them to go to, specifically? How many decimals, etc?

If you want always 2 decimals, try a standard numeric formatting such as:

decimal value = 123.456;
Console.WriteLine("Your account balance is {0:F}.", value);

See this MSDN example for other common numeric formatting techniques.

Upvotes: 2

Related Questions