Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Casting

Tags:

c#

formatting

I have a decimal number like this:

62.000,0000000

I need to cast that decimal into int; it will always have zero decimal numbers; so I wont loose any precision. What I want is this:

62.000

Stored on an int variable in c#.

I try many ways but it always give me an error, that the string isn't in the correct format, this is one of the ways i tryied:

int.Parse("62.000,0000000");

Hope you can help me, thanks.

like image 252
lidermin Avatar asked Mar 17 '26 12:03

lidermin


2 Answers

You need to parse it in the right culture. For example, the German culture uses "." as a group separator and "," as the decimal separator - so this code works:

CultureInfo german = new CultureInfo("de-DE");
decimal d = decimal.Parse("62.000,0000000", german);
int i = (int) d;

Console.WriteLine(i); // Prints 62000

Is that what you're after? Note that this will then fail if you present it with a number formatted in a different culture...

EDIT: As Reed mentions in his comment, if your real culture is Spain, then exchange "de-DE" for "es-ES" for good measure.

like image 122
Jon Skeet Avatar answered Mar 19 '26 01:03

Jon Skeet


You need to specify your culture correctly:

var ci = CultureInfo.CreateSpecificCulture("es-ES");
int value = (int) decimal.Parse("60.000,000000", ci);

If you do this, it will correctly convert the number.

like image 21
Reed Copsey Avatar answered Mar 19 '26 01:03

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!