3

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?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
D B
  • 296
  • 6
  • 27

2 Answers2

7

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!

Community
  • 1
  • 1
SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • 3
    Why is not a good idea storing currency as double? Maybe you should explain that in your answer :) – Pikoh Oct 28 '16 at 08:02
  • @Pikoh I think [this](http://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when) will answer to your question. – SᴇM Oct 28 '16 at 08:04
  • I know the answer SeM. I was suggesting you to explain that in your answer to complete it – Pikoh Oct 28 '16 at 08:05
  • 3
    @SeM - it's best that you edit your answer to include the reason for using `decimal` and then add to it also the link – Gilad Green Oct 28 '16 at 08:06
3
if(decimal.Parse(newPrice, System.Globalization.NumberStyles.Currency) >= decimal.Parse(oldPrice, System.Globalization.NumberStyles.Currency)){
  //    Do something here
}

Whilst you can also use double.Parse(...) it is not a good idea to store currency in a float as they are actually stored as base-2 numbers, whereas we care about base-10 numbers when we’re talking about money. Therefore they cannot represent some decimal values, so they round in ways you don’t expect. The last thing you want when performing maths on currency values is to lose money due to rounding!

See here for a more detailed explanation.

Community
  • 1
  • 1
connectedsoftware
  • 6,987
  • 3
  • 28
  • 43