-1

I'm converting a string to a decimal with decimal.Parse():

decimal.Parse(transactionAmount)

If transactionAmount contains a whole number such as 1, the result is a decimal value of 1. The system I'm sending it to outside of my program treats it as 1 cent for some unknown reason unless it shows up as 1.00. How can I make sure that whole numbers contain a decimal point and a zero such as 1.0?

Red
  • 26,798
  • 7
  • 36
  • 58
Rich
  • 6,470
  • 15
  • 32
  • 53
  • 3
    If you are sending the `string` rather than the `decimal` you can format the `decimal` value with decimal places as needed and send that. If you are sending the `decimal` then the question gets stranger. – HABO Jul 16 '20 at 15:53

2 Answers2

2

decimal contains number of digits after the point as part of its internal presentation. So 1m and 1.00m are different `decimal values. As result all parsing/formatting operations will try to preserve that information coming from/to string form unless forced otherwise.

One hack to make sure there are at least two digits after decimal separator is to add proper 0 - 0.00m:

    decimal decimalOne = decimal.Parse("1"); // 1.
    decimal decimalWithTwoDigit = decimalOne + 0.00m; // 1.00

Note that it is unusual to be sending decimal values in binary form to outside programs. Most likely you actually need to format decimal value with two digits only as covered in Force two decimal places in C# - .ToString("#.00").

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
-1

Try Convert.ToDecimal() instead of decimal.Parse()

Dan
  • 41
  • 6