Answered Trouble in parsing AE currency price to double value

Post number 24 has been selected as best answer.

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,575
Location
Virginia Beach, VA
Programming Experience
10+
No, OP's problem is that the currency symbol in input is incorrect.
Yes, I gathered that from the SO comments and answers. GIGO.

And so since it was a bad input issue, I figured I would start from scratch by going from decimal to a currency string and then back again. I started getting the same error as the OP which I didn't expect. I would have thought that MS would at least be able to round trip something that it generated. It took adding in the trailing whitespace flag to finally get it to round trip.
 

Sheepings

Senior Programmer
Staff member
Joined
Sep 5, 2018
Messages
1,378
Location
UK
Programming Experience
10+
There are a lot of things Microsoft do that leaves me scratching my head Skydiver. Including breaking their own object orientation rules as well as reusable code not being used. Take that enum topic the other day as proof of bad designing principles. That was just dumb thinking, so yes, I agree with you when you said
I would have thought that MS would at least be able to round trip something that it generated.
Its sometimes to be expected. That's Microsoft for you.
 

Palak Shah

Active member
Joined
Apr 29, 2020
Messages
40
Programming Experience
1-3
Woohoo! I got it to work!
C#:
var culture = new CultureInfo("ar-AE");
var value = 259.00m;

var s = value.ToString("C", culture);
MessageBox.Show(s);

var flags = NumberStyles.AllowCurrencySymbol |
            NumberStyles.AllowDecimalPoint |
            NumberStyles.AllowThousands |
            NumberStyles.AllowLeadingWhite |
            NumberStyles.AllowTrailingWhite;
var v = decimal.Parse(s, flags, culture);
MessageBox.Show(v.ToString("C", culture));
The magic are in lines 10-11.
This has worked!!1 wohooo :)
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
777
Location
Norway
Programming Experience
10+
I would have thought that MS would at least be able to round trip something that it generated. It took adding in the trailing whitespace flag to finally get it to round trip.
Leading/trailing white depends on culture, for my culture I had to add leading white. It's easier to just use the composite NumberStyles.Currency for currency strings:
C#:
var culture = new CultureInfo("ar-AE");
var value = 259.00m;
var s = value.ToString("C", culture);
value = decimal.Parse(s, NumberStyles.Currency, culture);
It won't work with broken input as in post 1 of course.
 
Top Bottom