Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

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.

What is the right formatting type to my case?

Upvotes: 0

Views: 871

Answers (3)

Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

I attributed the casting responsibility to database. I'm using MySQL and the query is like this:

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.

Upvotes: -1

Jeff LaFay
Jeff LaFay

Reputation: 13350

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")

Upvotes: 2

pascalhein
pascalhein

Reputation: 5866

You probably want to divide the number by 100 first (remember to change the type), so 150 becomes 1.50, which gets converted to "1,50" depending on locale:

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

Upvotes: 2

Related Questions