skip to Main Content

i am trying to round off value to two decimal places. but the issue is 0 at second is not appearing , it only shows decimal after one place.

i have fetched data from oracle db as 180.700 but while fetching it from db it shows only 180.7 in datatable after binding

 using (OracleConnection con = new OracleConnection(constr_ipdmdm))
            {
                using (OracleCommand cmd = new OracleCommand(query))
                {
                    using (OracleDataAdapter sda = new OracleDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                        }
                    }
                }
            }

while rounding it off to two decimal places it shows only one value after decimal i.e 180.7

Math.Round(Convert.ToDecimal(dt_spec.Rows[2]["YS"]), 2)

how can we show as 180.700 while binding it in datatable
and how can we round it two two decimal place i.e 180.70

Any idea would be appreciated.

2

Answers


  1. Preface: I know nothing about C#. I do have a logic suggestion though! Consider interpreting/casting the number as a string/chararray, and concatenating a bunch of zeros to the end of the string. Then, cast back to floating point, and do the roundoff. There should be another zero there.

    I’m not very familiar with the functions being used, but this logic has worked in the past in other languages.

    Login or Signup to reply.
  2. You can get oracle to round and format it

    TO_CHAR(numbercolumn, 'FM999990D00')
    

    This converts to a string in oracle so your c# app will receive a string. If you need to work with it numerically in c# you could have oracle round it instead

    ROUND(numbercol, 2)
    

    But depending on what you’re doing it may be best to leave the precise decimals on and do all your work with it then format it at the end of the work

    calculatedResult.ToString("0.00")
    
    $"{calculatedResult:0.00}"
    
    string.Format("{0:0.00}", calculatedResult)
    

    You don’t need to Math.Round it first. Formatting 1.2355 as "0.00" becomes "1.24"


    If you’re using this datatable of yours in something like a windows forms DataGridView then it’s the job of the grid to format the data, not on you to change it to a string. Look at something like

    TheDgv.Columns[TheColumnIndex].DefaultCellStyle.Format = "0.00";
    

    And make sure the data in the datatable column is numeric, not a string

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search