-1

I've retrieved a decimal value from database as a string:

string get_amt = dt_.Rows[i]["billing_amt"].ToString();

Values of billing_amt are 100.0000, 150.0000, 0.0000.

I tried to display the value of get_amt rounding up to two decimal places using the code:

string.Format("{0:0.00}", get_amt)

but it is not working. How can I show the value of get_amt as 100.00 or 150.00? Please suggest.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user4221591
  • 2,084
  • 7
  • 34
  • 68
  • 2
    I suggest you actually **convert the values to decimal** and then you can display them any way you want. ... you should *always* use the appropriate data type - and for a decimal, that's **not** a string ..... – marc_s Feb 01 '17 at 09:36
  • Is not there any other way? – user4221591 Feb 01 '17 at 09:39
  • 1
    `double x = 100.0000; Console.Write(x.ToString("N2"));` – Wiktor Stribiżew Feb 01 '17 at 09:39
  • Check out this old answer from SO, maybe it will help you: [Link](http://stackoverflow.com/questions/6951335/using-string-format-to-show-decimal-upto-2-places-or-simple-integer) – PinHead877 Feb 01 '17 at 09:40

2 Answers2

0

You'll probably want to try something like:

double get_amt = 0;

if (dt_.Rows[i]["billing_amt"] != DBNull.Value)
    get_amt = Convert.ToDouble(dt_.Rows[i]["billing_amt"]);

Then:

string.Format("{0:0.00}", get_amt)  

should work.

It's currently not working as it's a string value your trying to format - which wont have decimal places.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Scott
  • 180
  • 6
  • 2
    You should **avoid** using the `double` or `float` types - use `decimal` to avoid rounding errors! – marc_s Feb 01 '17 at 09:43
0

Strictly speaking, you could use Regex to cut the string down to a 2 decimal point number like so:

string formatted = Regex.Match(unformattedString, @"^-?\d+\.\d{2}").Value;

That being said, you almost never want to use a string to hold number information. It's a bother and a pain to get them to do what you want. It's much more advisable to store them as either a double or a decimal, then convert to string only when you have to.

Abion47
  • 22,211
  • 4
  • 65
  • 88
  • Avoid `double` (or `float`) - use `decimal` to avoid rounding errors – marc_s Feb 01 '17 at 09:43
  • @marc_s Unless you need a high level of precision, `double` isn't likely to cause any rounding issues significant enough to really do much. And if OP only needs the values to the second decimal point, I'd say that `double` is fine. – Abion47 Feb 01 '17 at 09:45