Pergunta

Hi I can't find any good way to format this string to a decimal.

3942.000000000000

Any ideas on it?

EDIT
How is this now a valid question? Some (as I) might miss the CultureInfo that's suppose to go in the decimal.Parse, for just different culture formats.

Also I didn't want a float, so making a float to decimal is extra steps. Just my two cents

Foi útil?

Solução

Have you tried Decimal.Parse with specifying decimal separator?

var yourString = "3942.000000000000";
var info = new NumberFormatInfo { NumberDecimalSeparator = "." };
var parsed = Decimal.Parse(yourString, info);

EDIT: as Jon suggested you can use InvariantCulture:

var yourString = "3942.000000000000";
var parsed = Decimal.Parse(yourString, CultureInfo.InvariantCulture);

Outras dicas

Any reason you cannot use

Convert.ToDecimal("3942.000000000000");

You can use TryParse on the string. Please note the out in the call.

string yourString = "3942.0000000000"
decimal yourDecimal;
decimal.TryParse(yourString, out yourDecimal)

You can use TryParse:

string yourString = "3942.0000000000"

decimal d;
if (decimal.TryParse(yourString, out d))
{
     //OK
}
else
{
     // Handle failure
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top