在 C# 中将字符串类型转换为货币
本文关键字:类型转换 货币 字符串 | 更新日期: 2023-09-27 18:35:47
我正在尝试获取 TR 的字符串输入和字符串 PMP 将它们转换为货币,然后相乘以获得美元货币的输出。
string SP; // Sales Price
string TR; //Total Revenue
string PMP; //Property management percentage
string PMF; //Property Management Monthly Fee
Console.WriteLine("What is the total rent revenue?");
TR = Console.ReadLine();
Console.WriteLine("what is the percentage you pay to property managment?");
PMP = Console.ReadLine();
Console.WriteLine("you will be buying {0}", PMF );
SP = Console.ReadLine();
TR = Console.ReadLine();
PMP = Console.ReadLine();
PMF = string.Format("{TR:C,PMP:C}") <------- THIS IS WHERE I AM TRYING TO CONVERT AND MULTIPLY****
任何帮助都将不胜感激。谢谢
PS 我不是职业程序员(主要是网络工程和服务器管理员),这是我进入编程的前 20 个小时。
如果是我,我会首先创建一个方法来从用户那里获取有效的十进制数(因为我们这样做了几次,并且当用户输入无效条目时,它应该有一些错误处理)。像这样:
public static decimal GetDecimalFromUser(string prompt,
string errorMessage = "Invalid entry. Please try again.")
{
decimal value;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out value)) break;
if (errorMessage != null) Console.WriteLine(errorMessage);
}
return value;
}
然后,我将调用此方法从用户那里获取输入,执行所需的计算(您没有指定公式,所以我是即兴创作),并将值输出给用户:
decimal totalRevenue = GetDecimalFromUser("Enter the monthly rent revenue: $");
decimal propMgmtPct = GetDecimalFromUser("Enter the percentage you pay " +
"for property management: ");
decimal propMgmtFee = totalRevenue * propMgmtPct;
Console.WriteLine("The monthly property management fee will be: {0}",
propMgmtFee.ToString("C2", CultureInfo.CreateSpecificCulture("en-US")));
Format
语法更像是string.Format("{0:C},{1:C}", TR, PMP)
。- 您只能设置数字类型的格式,例如这样的
decimal
。请考虑decimal.TryParse
以查看用户键入的内容是否看起来像数字,然后设置结果数字的格式。 - 对于乘法,您当然需要数字类型,例如
decimal
,并且您使用星号符号*
作为乘法运算符。