D B - 2 months ago 9

C# Question

I am wondering how i would compare 2 Prices as datatype string.

Example;

`string oldPrice = "£1.99";`

string newPrice = "£2.50";

I want to compare if the newPrice is >= to oldPrice but im unsure how to convert the string into a decimal/int. Taking off the £ sign.

Any ideas? hints or tips on how to tackle this?

Answer

This should work:

```
string oldPrice = "£1.99";
decimal result = decimal.Parse(oldPrice, System.Globalization.NumberStyles.Currency);
```

Storing currency as a `double`

is **not** a good idea, and it would be better to use `decimal`

instead. The decimal type is only more accurate at representing base 10 numbers (e.g. those used in currency/financial calculations). In general, the double type is going to offer at least as great precision and definitely greater speed for arbitrary real numbers.
Also check out this and this links for more information where and when to use `decimal`

or `double`

.

Also check out @Triynko's comment from here:

Here's why you use Decimal for money: Double's accuracy is only 16 decimal digits, and after just a few arithmetic ops, errors will quickly accumulate large enough to creep into the 15, 14, 13, etc. digits. Rounding to "cents" requires at least one digit of full accuracy after cents digit, but really you should reserve 4 or 5 to insulate from cumulative arithmetic errors, which you CANNOT allow to corrupt the hundredths column you use to round the cents. That leaves you with 16 (total) - 2 (cents) - (4 or 5 error padding) = oh $hit only 7 (or less) reliable integer digits for your money!