简体   繁体   English

如何从数据库格式化货币

[英]How to format currency from database

The goal 目标

I want to format correctly the currency from database. 我想从数据库中正确格式化货币。

The problem 问题

I'm formatting the currency from database with this: 我正在使用此格式从数据库格式化货币:

@String.Format("{0:C}", @Model["MinProductPrice"])

The problem is: 150 have to be 1,50 , and not 150,00 — and this formatting is doing this. 问题是: 150必须是1,50 ,而不是150,00 —而这种格式就是这样做的。

What is the right formatting type to my case? 什么是适合我的情况的正确格式类型?

您可能想先将数字除以100(请记住要更改类型),因此150变为1.50 ,根据语言环境,该值将转换为"1,50"

@String.Format("{0:C}", @Model["MinProductPrice"] / 100.0m)

I'll extend my comments into an answer, I think that's more appropriate. 我将我的评论扩展为答案,我认为这更合适。 I think you should change the column type to a money or decimal type to prevent bugs by making the use of the column more obvious. 我认为您应该将列类型更改为金钱或十进制类型,以通过使列的使用更加明显来防止错误。 Your output on your page will be correct and won't require any "magic numbers" to get it to print out properly. 您在页面上的输出将是正确的,并且不需要任何“魔术数字”即可正确输出。

Just a note but you can also print a currency string doing this: 只是一个注释,但您也可以执行以下操作来打印货币字符串:

@Model["MinProductPrice"].ToString("C")

I attributed the casting responsibility to database. 我将转换责任归因于数据库。 I'm using MySQL and the query is like this: 我正在使用MySQL,查询如下:

ROUND(CAST(MIN(`map`.`Product_Price`) AS DECIMAL)/100,2) as `minProductPrice`

Anyway, I would to thanks jlafay and csharpler about their answers — they were very helpful and worked well for me. 无论如何,我要感谢jlafaycsharpler的回答-他们非常乐于助人,并且对我来说很好。

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

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