如何在.NET中格式化十进制类型时删除小数部分?我需要两种变体的通用语法。有没有温和的解决方案?
decimal a = 1.22M;
decimal b = 1.00M;
String.Format("${0}", a); // result is $1.22
String.Format("${0}", b); // result is $1.00, should be $1, HOW?
答案 0 :(得分:7)
假设'通用语法'意味着您需要一个解决方案来提供两个输出,String.Format("${0:#.##}", x)
就可以了。当x
为1.00M
时,结果为"$1"
。当x
为1.22M
时,结果为"$1.22"
。
答案 1 :(得分:4)
尝试这些 - 两者都将输出当前系统的相应货币符号:
a.ToString("C2"); // Outputs 2DP
b.ToString("C0"); // Outputs no DP
如果您需要提供特定的货币符号,请使用与上述相同的内容,但将N替换为C.
答案 2 :(得分:2)
Decimal
类型旨在跟踪其拥有的有效位数。这就是1.00M.ToString()
返回字符串1.00
。
要打印没有派系部分的Decimal
,您可以使用格式说明符N
,精确0
:
1.22M.ToString("N0") => "1"
1.00M.ToString("N0") => "1"
1.77M.ToString("N0") => "2"
这会转换转化过程中的Decimal
。
答案 3 :(得分:2)
在VB.NET中我会使用
CINT(INT(a))
我想象存在一个C#变体。
我在这个链接上找到了一个可能的解决方案:
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
进一步解释:
decimal a = 1.55M;
Console.WriteLine("$" & CInt(Int(a)).ToString()); // result is $2
decimal b = 1.22M;
Console.WriteLine("$" & CInt(Int(b)).ToString()); // result is $1
我会避免使用货币格式,因为小数是该类固有的。
答案 4 :(得分:0)
string.Format("${0:0}",b)
在C#中,您可以使用{0}
来告诉参数,并使用{0:format}
告诉参数格式。
修改强>
哦,我认为OP想要做的是删除b的数字。但现在我意识到他想要删除无用的零。
string.Format("${0:#.##}",b)
答案 5 :(得分:0)
我认为还有其他问题。如果问题是完全忽略小数位,那么只需转换为整数就会产生所需的输出,但显然会失去精度,这不是一件好事。
在格式化为字符串时,还存在舍入注意事项,如下例所示。
decimal a = 1.55M;
Console.WriteLine(a.ToString("C0")); // result is $2
decimal b = 1.22M;
Console.WriteLine( b.ToString( "C0" ) ); // result is $1
答案 6 :(得分:0)
我认为这只是用于显示而当数字在小数点后没有值时,不会将数据类型更改为INT。
使用System;
namespace stackOverflow
{
class Program
{
static void Main(string[] args)
{
decimal a = 1.2245M;
decimal b = 1.00M;
Console.WriteLine("Your percentage to date is: {0:#.#####}", a);
Console.WriteLine("Your percentage to date is: {0:#.#####}", b);//#.#### gives number upto 4 decimal
Console.ReadLine();
}
}
}
答案 7 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double n, x;
int a, dec = 0;
Console.WriteLine("Enter double");
n = Convert.ToDouble(Console.ReadLine());
a = Convert.ToInt32(n);
x = n - a;
if (x < 0)
a--;
int k = 1000;
for (int i = 0; i < n.ToString().Length; i++)
{
if (n.ToString()[i] == '.')
k = i;
if (i > k)
dec = dec * 10 + (n.ToString()[i]-48);
}
Console.WriteLine("Non-fraction " + a);
Console.WriteLine("Fraction " + dec);
Console.ReadKey();
}
}
}