将视图中的值格式化为货币

问题描述 投票:0回答:1

我正在尝试将 API 返回中的几行显示为货币。视图的代码如下,我不确定是否可以在线执行此操作,或者是否需要在将其传递到视图之前执行此操作。表中的最后两行需要是货币。

 @model Final_Project.Models.Root

<h2>Card Info</h2>


<table class="table" >
    <tr>
        <th>Name</th>
        <th>Variant</th>
        <th>Card Number</th>
        <th>Rarity</th>
        <th>Artist</th>
        <th>High Price</th>
        <th>Low Price</th>
        <th>Market Price</th>

    </tr>

    @foreach (var product in @Model.results)
    {
        <tr>
            <td>@product.name</td>
            <td>@product.variant</td>
            <td>@product.cardNumber</td>
            <td>@product.rarity</td>
            <td>@product.artist</td>
            <td>@product.prices.tcgPlayer[1].high.amountInMinorUnits</td>
            <td>@product.prices.tcgPlayer[1].low.amountInMinorUnits</td>
            <td>@product.prices.tcgPlayer[1].market.amountInMinorUnits</td>
        </tr>
    }
</table>

我尝试过像这样格式化其中一行

<td>@(product.prices.tcgPlayer[1].market.amountInMinorUnits / 100).ToString("C2")</td>
我的回答是
3.ToString("C2")
。那显然不是货币;)。

model-view-controller view
1个回答
0
投票

要在 Razor 视图中将数值格式化为货币,可以使用 @String.Format 方法或 @: 指令来指定格式。就您而言,您尝试将 amountInMinorUnits 格式化为货币。假设 amountInMinorUnits 表示以小单位(例如美分)表示的货币金额,您可以将其转换为美元并将其格式化为货币,如下所示:

html

<td>@(product.prices.tcgPlayer[1].market.amountInMinorUnits / 100)</td>

但是,您遇到的问题(3.ToString("C2"))表明您正在格式化的值不是数字类型,而是字符串。在这种情况下,您需要先将其解析为数字类型(例如小数),然后再将其格式化为货币。具体方法如下:

html

<td>@(decimal.Parse(product.prices.tcgPlayer[1].market.amountInMinorUnits) / 100).ToString("C2")</td>

此代码将首先将 amountInMinorUnits 字符串解析为小数(假设它包含有效的数值),然后将其格式化为货币。

如果您不确定该值在所有情况下是否都是有效数字,您可能需要添加一些错误处理来处理解析失败的情况。下面是使用decimal.TryParse 方法进行错误处理的示例:

html

    @{
        decimal marketPrice = 0;
        decimal.TryParse(product.prices.tcgPlayer[1].market.amountInMinorUnits, out marketPrice);
    }

<td>@(marketPrice / 100).ToString("C2")</td>

此代码尝试解析该值,如果解析失败,则会将 marketPrice 设置为 0。您可以调整错误处理逻辑以满足您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.