- Home /
How to set fixed number of digits?
I was wondering if there was a clean and short way to make a certain integer always to show with three digits, even if it is lower than 100 (i.e. 003, 005, 012, 057, 099). I do not like doing it like this:
if (i < 100) { if (i < 10) { someString = "00" + i.ToString(); } else someString = "0" + i.ToString(); } else { someString = i.ToString(); }
Answer by Bork Awesome · Sep 04, 2012 at 10:30 AM
The 'Dn' parameter of ToString() specifies the number of leading 0's; so for your example, requiring 3 leading zero's, the code would be:
threeDigitString = i.ToString("D3");
See the reference here: http://msdn.microsoft.com/en-us/library/dd260048.aspx
I am using Unity 5 and the "D3" formatter threw up an error.
For reference, "F2" is what worked for me, whereas "D3" threw an error.
I'm using Unity 2020.1.0b8.3654 I used "d2" with no problems.
string seconds = ((int)round1Timer % 60).ToString("d2");
Answer by TheGameLearner · Apr 13, 2018 at 04:12 AM
i.ToString("D3") May not always work in Unity, but you have custom options that can be filled in as
int i = 23;
print("3 digit num = " + i.ToString("000") );
The same can be used to ensure padding for a minimum number of digits however many they might be.
Your answer
Follow this Question
Related Questions
Dealing with Texture2D.width as it is a float number 3 Answers
Float to int casting in C# script with modulo giving division by zero error 1 Answer
How to break up a number into seperate digits? 2 Answers
Really weird behaviour with boolean variables from custom class 2 Answers
Idle Game Currency Optimizing 1 Answer