How do I format a double to currency rounded to the nearest dollar?

后端 未结 6 1068
春和景丽
春和景丽 2020-12-05 03:58

Right now I have

double numba = 5212.6312
String.Format(\"{0:C}\", Convert.ToInt32(numba) )

This will give me

$5,213.00


        
相关标签:
6条回答
  • 2020-12-05 04:26
    Console.WriteLine(numba.ToString("C0"));
    
    0 讨论(0)
  • 2020-12-05 04:29

    I think the right way to achieve your goal is with this:

    Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalDigits = 0;
    

    and only then you should do the Format call:

    String.Format("{0:C0}", numba) 
    
    0 讨论(0)
  • 2020-12-05 04:30

    This should do the job:

    String.Format("{0:C0}", Convert.ToInt32(numba))
    

    The number after the C specifies the number of decimal places to include.

    I suspect you really want to be using the decimal type for storing such numbers however.

    0 讨论(0)
  • 2020-12-05 04:31
     decimal value = 0.00M;
            value = Convert.ToDecimal(12345.12345);
            Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
            Console.WriteLine(value.ToString("C"));
            //OutPut : $12345.12
            Console.WriteLine(value.ToString("C1"));
            //OutPut : $12345.1
            Console.WriteLine(value.ToString("C2"));
            //OutPut : $12345.12
            Console.WriteLine(value.ToString("C3"));
            //OutPut : $12345.123
            Console.WriteLine(value.ToString("C4"));
            //OutPut : $12345.1235
            Console.WriteLine(value.ToString("C5"));
            //OutPut : $12345.12345
            Console.WriteLine(value.ToString("C6"));
            //OutPut : $12345.123450
    

    click to see Console Out Put screen

    Hope this may Help you...

    Thanks. :)

    0 讨论(0)
  • 2020-12-05 04:36

    First - don't keep currency in a double - use a decimal instead. Every time. Then use "C0" as the format specifier:

    decimal numba = 5212.6312M;
    string s = numba.ToString("C0");
    
    0 讨论(0)
  • 2020-12-05 04:45

    simple: numba.ToString("C2")

    more @ http://msdn.microsoft.com/pt-br/library/dwhawy9k(v=vs.110).aspx#CFormatString

    0 讨论(0)
提交回复
热议问题