如何让结果保留小数点后四位

houzhiweisz 2011-04-18 08:40:18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyTest
{
class Test
{

static void Main(string[] args)
{
float price1 = 27.3f;
float price2 = 57.0f;
int n1 = 2;
int n2 = 3;
float discount = 0.2f;
double total = price1 * n1 + price2 * n2;
if (total > 200 || (price1 > 100 && price2 > 100))
{
total = total * (1 - discount);
Console.WriteLine("折后总消费金额为:{0}", total);

}
else
Console.WriteLine("总消费金额为:{0}", total);



Console.ReadKey();
}

}
}
...全文
840 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
crapex 2011-04-18
  • 打赏
  • 举报
回复
改成
Console.WriteLine("总消费金额为:{0:f4}", total);
就可以了
使用参数时,直接在参数后用冒号加格式化字串就行
houzhiweisz 2011-04-18
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyTest
{
class Test
{

static void Main(string[] args)
{
decimal price1 = 27.3M;
decimal price2 = 57.0M;
int n1 = 2;
int n2 = 3;
decimal discount = 0.2M;
decimal total = price1 * n1 + price2 * n2;

if (total > 200 || (price1 > 100 && price2 > 100))
{
total = total * (1 - discount);

Console.WriteLine("折后总消费金额为:{0}", total);

}
else
Console.WriteLine("总消费金额为:{0}", total);



Console.ReadKey();
}

}
}小数点后是2位?
duan_dream 2011-04-18
  • 打赏
  • 举报
回复
金额用decimal 不是挺好的吗? 自动就是4位了。。。
weishaolin131083 2011-04-18
  • 打赏
  • 举报
回复
建议你用 decimal 类型,
尽量不要用 double .
weishaolin131083 2011-04-18
  • 打赏
  • 举报
回复
total .ToString("f4");

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧