Search code examples
c#asp.netasp.net-mvc-5bitcoinint64

How to format Int64 values to currency


i am developing an application, where i save money values in the database as int64.

For example, if i save 1 euro in the database, it gets saved as 100 cents. When I read the value, how can i format it so it gets displayed like this:

db value / output
100000 = 1,000.00
10000 = 100.00
1000 = 10.00
100 = 1.00
10 = 0.10
1 = 0.01

I experimented with string.format but I am unable to get the results i need... Your help will be appreciated, thank you very much.


Solution

  • You can create a custom NumberFormatInfo object with required properties and use it to format the output. Below code does not assume the value is coming from database, but there should be no difference:

    // Create custom number format
    NumberFormatInfo nfi = new NumberFormatInfo();
    nfi.NumberDecimalSeparator = ".";
    nfi.NumberGroupSeparator = ",";
    // You can also set property NumberDecimalDigits to the number of decimal digits that you need:
    nfi.NumberDecimalDigits = 2;
    
    // Output the results
    long textValue = 123456789;
    Console.WriteLine((textValue/100m).ToString("N", nfi));
    

    Because you are storing value using round numbers in the output number is divided by 100 to get the actual value