浮点值应保留 2 位小数
我得到的输出为 756.4
但这等于 756.40
我知道这一点,但我仍然想将其保存为 756.40
那么如何才能我将其转换为所需的
忘记提及我的 totalamount
被声明为 float
Amount[index]
//In this amount is returned as arraylist
totalAmount += float.Parse(Amount[index].ToString());
Here after all additons done after the循环我想得到所需的一个
转换示例代码
if (totalAmount.ToString().Contains("."))
{
string[] b = totalAmount.ToString().Split('.');
Dollars = b[0].ToString().PadLeft(10, (char)48);
cents = b[1].ToString().PadRight(2, (char)48).Substring(0, 2);
}
else
{
Dollars = totalAmount.ToString().PadLeft(10, (char)48);
cents = "00";
}
FormattedTotalAmounts = Dollars + cents; // Here i am getting the output as i said
I am getting the output as 756.4
but this is equal to 756.40
i know that but still i would like to save it as 756.40
so how can i convert that to the required one
Forgot to mention my totalamount
is declared as float
Amount[index]
//In this amount is declared as arraylist
totalAmount += float.Parse(Amount[index].ToString());
Here after all additons done after the loop i would like to get the required one
A sample code of conversion
if (totalAmount.ToString().Contains("."))
{
string[] b = totalAmount.ToString().Split('.');
Dollars = b[0].ToString().PadLeft(10, (char)48);
cents = b[1].ToString().PadRight(2, (char)48).Substring(0, 2);
}
else
{
Dollars = totalAmount.ToString().PadLeft(10, (char)48);
cents = "00";
}
FormattedTotalAmounts = Dollars + cents; // Here i am getting the output as i said
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这会将总金额格式化为具有两位小数 (
2
) 的定点数 (F
)。有关这些格式字符串的详细信息,请参阅以下两篇 MSDN 文章:This formats the total amount as a fixed-point number (
F
) with two decimal places (2
). For details about these format strings, see the following two MSDN articles:在你的代码中改变这个
In your code change this
试试这个:
Try this:
您可以在 ToString 中使用数字格式,例如
you can use numberformat in your ToString like
首先,我认为如果这是财务数据,您可能应该使用
Decimal
。其次,数值没有尾随空格,而字符串有。
编辑:添加了 C# 2.0 标记 - 删除了 LINQ。
将“F”传递给 ToString 同样有效。
编辑回复评论。
左边有 10 个 0,右边有 2 个 0。
First, I think you should probably be using
Decimal
if this is financial data.Second, numeric values don't have trailing spaces, strings do.
EDIT: C# 2.0 tag added - LINQ removed.
passing "F" to ToString will work equally well.
EDIT responding to comment.
gives 10 0's on the left and 2 0's on the right.