How can the numbers from 1 to 9 give this view 01, 02, 03 using php or javascript?
- You probably meant javascript , not java ? - Dmitriy Simushev
- yeah, mistake)) - Alex Prosto
|
3 answers
For formatted data output in php, you can use the function sprintf ()
Example:
<?php for ($i = 0; $i < 20; $i++) { echo sprintf("number - %'.02d", $i).'<br>'; } echo sprintf("number - %'.02d", 247).'<br>';
Result:
number - 00 number - 01 number - 02 number - 03 number - 04 number - 05 number - 06 number - 07 number - 08 number - 09 number - 10 number - 11 number - 12 number - 13 number - 14 number - 15 number - 16 number - 17 number - 18 number - 19 number - 247
|
PHP has a concatenation operator:
$num = 1; echo('0' . $num);
And in JavaScript, you can explicitly cast a number to a string:
var num = 1; console.log('0' + num.toString());
- Honestly weak in languages, for example, I have $ as, which is equal to 1,2,3,4, .... 12,13,14 .... and how to make it so that zeros from 1 to 9 are added? ? - Alex Prosto
- see @Visman's answer - Dmitriy Simushev
|
Since there is a js mark here, and everything about js is silent, then:
function conv(n) { return ("0"+n).slice(-2); } [0,1,58,99,101].map(conv) == "00,01,58,99,01" // true
I pay attention that the three-digit number was cut off to two last signs.
- For what a minus? - Qwertiy ♦
- Most likely for a strange decision :) Even
num > 9 ? num : '0' + num
num > 9 ? num : '0' + num
will work much better - vihtor - @vihtor, I warned how it works. Adding zero in most cases is necessary for formatting a date or time, and there are no three-digit numbers, so this behavior is a bit complicated to call wrong. - Qwertiy ♦
- Well, so you offer part of the solution, that is, you can not just take it and start using it. it is necessary to add to it a condition that will not give more than 99 numbers to the processing of the function
conv
. and this strange solution is vihtor - @vihtor, in dates there are no numbers greater than 99. Even more than 60 are not. And as a bonus, you can trim a year to two characters, if you want (and if you don’t, then there is no reason to call it for a year). - Qwertiy ♦
|