-7

In C#, I have a custom string "12.10", when I convert it to decimal it is converted as 12.1 but I need it to be 12.10 in decimal also, please help

Below is the code

 string Value = nudEngineeringYears.Value + "." + nudEngineeringMonths.Value;
 selStaff.EngineeringExperience = Convert.ToDecimal(Value);
Pradeep
  • 7
  • 1

4 Answers4

2

There is no difference between a decimal with value 12.1 or value 12.10.

If you want to display the decimal with 2 decimal place, specify a format string in ToString:

myDouble.ToString("0.00");
Rik
  • 28,507
  • 14
  • 48
  • 67
1

Well, as math stays

12.1 == 12.10 == 12.100 == ...

etc. However, you can change number's representation as a string by formatting:

  12.1.ToString("F2"); // <- return 12.10 (note "2" in formatting string)
  12.1.ToString("F3"); // <- return 12.100 etc.
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

There's no decimal 12.10, only 12.1.

What you're talking about when you say 12.10 is a possible representation of that value.

There's no difference between 12.10 and 12.1 when talking about numbers, but there's a difference between the string "12.10" and the string "12.1".

So don't confuse a number with its representation (which typically only matters in the front end).

If you want to format your value, you create a string representation of it. See Standard Numeric Format Strings.

sloth
  • 99,095
  • 21
  • 171
  • 219
1

You seem to confuse the internal/binary representation of a floating point number with its representation when converted to a string.

Internally a float has always about seven places of precission, a double about 15 places of precission, a decimal even more.

Only when you format such a binary value to a string you may specify the number of places shown. For formatting use .ToString(format) with the format you need. in your case "F2"

DrKoch
  • 9,556
  • 2
  • 34
  • 43