How to format numbers differently depending on their value in C #?

I have an integer that I will store in a string according to the following rules:

  • If the number is less than 10, then it should be in front of it 0.
  • If it is greater than 10, save it without a leading 0.

How to do it in C #?

+3
source share
6 answers

You can use:

String.Format("{0:D2}", myInt);

": D2" tells String.Format to insert the number into at least two digits, adding zeros. If it is longer than two digits, it will not do anything.

+3
source

You can use ToStringwith string:

var i = 6;
var stringRepresentation = i.ToString("d2");
+7
source

MSDN :

:

string formatted = myNumber.ToString("00");
+2

- : http://blog.stevex.net/string-formatting-in-csharp/

: String.Format("{0:0#}", <yourIntegerVariable>)

+2

If you already have a string, you can write

str = str.PadLeft(2, '0');

Please note that you can search

string str = new DateTime(1,1,1, 12,34,56).ToShortTimeString();

This returns 12:34 PMand can be customized using format strings .

+1
source
int i = 8;

string s = String.Format("{0:00}", i);

00 represents 2 digits 00.00 will represent 2 digits and 2 decimal places

0
source

Source: https://habr.com/ru/post/1786682/


All Articles