格式化十进制 C# - 保留最后一个零 [英] Format decimal c# - Keep last zero

查看:31
本文介绍了格式化十进制 C# - 保留最后一个零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这个,但似乎无法找到答案.我有以下小数和我想要的 String.Format

I have been searching for this but cannot seem to find the answer. I have the following decimals with the corresponding output that I want from String.Format

100.00 -> 100
100.50 -> 100.50
100.51 -> 100.51

100.00 -> 100
100.50 -> 100.50
100.51 -> 100.51

我的问题是,我似乎找不到一种格式,既可以在 100.50 的末尾保留 0,又可以从 100 中删除 2 个零.

My problem is that I cannot seem to find a format which will keep the 0 on the end of 100.50 as well as remove the 2 zeros from 100.

非常感谢任何帮助.

编辑为了更清楚一些.我有十进制类型的变量,它们只能保留 2 个小数位.基本上我想显示2个小数位,如果它们存在或不存在,我不想在100.50变成100.5的情况下显示一个小数位

EDIT For some more clarity. I have variables of type decimal, they are only ever going to be 2 decimal places. Basically I want to display 2 decimal places if they exist or none, I don't want to display one decimal place in the case of 100.50 becoming 100.5

推荐答案

你可以使用这个:

string s = number.ToString("0.00");
if (s.EndsWith("00"))
{
    s = number.ToString("0");
}

这篇关于格式化十进制 C# - 保留最后一个零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆