0

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.

mxcoin
  • 13
  • 3
  • So what is the decimal and thousands separator? For thousand it is `.`, but for 100 it is `,` – dotnetom Feb 22 '15 at 19:36
  • What have you tried so far with string.format and what results did you get? Also, why does only the first example not follow european notation? – Sayse Feb 22 '15 at 19:37
  • i think 1 should be represented as 0.01 and not 0,01 right? – Monah Feb 22 '15 at 19:47
  • @HadiHassan It depends on the currency formatting for your culture. Some use a comma as a decimal separator. – Rufus L Feb 22 '15 at 20:14

2 Answers2

2

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

dotnetom
  • 24,551
  • 9
  • 51
  • 54
  • thank you for the answer. i will try it tomorrow. but if the stored value is for example 1000, i think with this method no .00 after the value get displayed? – mxcoin Feb 23 '15 at 00:42
  • @mxcoin It should display 10.00 if input 1000 is provided – dotnetom Feb 23 '15 at 07:19
  • okay, i used this method, it works for an euro value, but if i want to format a bitcoin value (8 digits after the point), it doesn't work. i changed the division to 100000000m. :( – mxcoin Feb 23 '15 at 17:31
  • @mxcoin I updated the answer to also use property `NumberDecimalDigits`. Update the number `3` to `8` in case of bitcoin – dotnetom Feb 23 '15 at 17:51
  • i experimented and had success with division to 100000000m and N8 in tostring. but your method is even cleaner. thank you very much. – mxcoin Feb 23 '15 at 17:55
0

Your easiest way to do this is probably to have SQL handle the conversion for you. Assuming you have SQL Server, you can simply use the function FORMAT(db_value/100.0,'#,##0.00')

https://msdn.microsoft.com/en-us/library/hh213505.aspx

Tim Cooke
  • 862
  • 7
  • 14