如何在C#格式化一个Int时强制标志 [英] How to force a sign when formatting an Int in c#

查看:138
本文介绍了如何在C#格式化一个Int时强制标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要格式化的整数i( -100 LT; I< 100 ),使得:

I want to format an integer i (-100 < i < 100), such that:

-99格式为-99结果
9格式为+09结果
-1格式为-01结果
0格式为 +00

-99 formats as "-99"
9 formats as "+09"
-1 formats as "-01"
0 formats as "+00"

i.ToString("00")

是接近,但不添加时,int是积极的+号。

is close but does not add the + sign when the int is positive.

有没有办法做到这一点没有
I>之间的明确区分; = 0 I< ?0

Is there any way to do this without explicit distinguishing between i >= 0 and i < 0?

推荐答案

试试这个:

i.ToString("+00;-00;+00");

当用分号(;)分隔的第一部分将适用于正面的价值观和零(0)时,第二部分将适用于负值,第三部分将适用于零(0)。

When separated by a semicolon (;) the first section will apply to positive values and zero (0), the second section will apply to negative values, the third section will apply to zero (0).

请注意,该第三部分可以省略,如果你想零为格式化为相同的方式正数。 。第二部分,也可以,如果你想底片格式一样阳性,但希望为零不同格式省略

Note that the third section can be omitted if you want zero to be formatted the same way as positive numbers. The second section can also be omitted if you want negatives formatted the same as positives, but want a different format for zero.

参考:的MSDN自定义数字格式字符串:本;节分隔符

这篇关于如何在C#格式化一个Int时强制标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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