简体   繁体   English

如何将Int64值格式化为货币

[英]How to format Int64 values to currency

i am developing an application, where i save money values in the database as int64. 我正在开发一个应用程序,在其中我将金钱值存储为int64。

For example, if i save 1 euro in the database, it gets saved as 100 cents. 例如,如果我在数据库中节省了1欧元,它将另存为100美分。 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. 我尝试使用string.format,但无法获得所需的结果...非常感谢您的帮助。

You can create a custom NumberFormatInfo object with required properties and use it to format the output. 您可以创建具有必需属性的自定义NumberFormatInfo对象,并使用它来格式化输出。 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 因为您正在使用舍入数字存储值,所以输出数将被100除以得到实际值

Your easiest way to do this is probably to have SQL handle the conversion for you. 最简单的方法可能是让SQL为您处理转换。 Assuming you have SQL Server, you can simply use the function FORMAT(db_value/100.0,'#,##0.00') 假设您有SQL Server,则只需使用函数FORMAT(db_value/100.0,'#,##0.00')

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM