0

How do I insert decimal point into string?

int attrval = Convert.ToInt32("000504");
decimal val1 = (attrval / 100);  
string val2 = String.Format("{0:.00}", attrval / 100);

val1 = 5 need 5.04

val2 = 5.00 need 5.04

Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
Paul
  • 93
  • 1
  • 10

2 Answers2

3

You have an issue with integer division in the line

 decimal val1 = (attrval / 100);  

Since both attrval and 100 are of type int the result is int as well: 5. This line should be

 decimal val1 = (attrval / 100m);

please, note m suffix: here we divide int by decimal (100m) and have a desired decimal result. Same for val2:

 string val2 = String.Format("{0:.00}", attrval / 100m);
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
1

Division of two integer numbers return integer value as a result. This division rounds resultant value towards zero, that is why you are getting val2 = 5 instead of 5.04.

If you want result to be in decimal type, convert at-least one value either numerator or denominator to the decimal.

decimal val1 = (attrval / (decimal)100);  //5.04

or

decimal val1 = (attrval / 100m);    //5.04

Now convert it into string,

string val2 = String.Format("{0:.00}", var1); //"5.04"

Try it online

Prasad Telkikar
  • 13,280
  • 4
  • 13
  • 37