Domanda

So i wanted to display a counter with each char wrapped in a tag and also add a thousands seprator.

The number must be atleast 3 char long.

Case 1:

I took a number 12

the code:

$number = 12 //number 12
$number = number_format($number, 0, '', ','); //add a thousand seprator
$number = str_pad($number,3,0,STR_PAD_LEFT); //pad if length less than 3
$counter = "";
foreach (str_split($number) as $key => $digit) {
    $counter .= '<b>' . $digit . '</b>';
}

Output: 012 (ignoring the <b> tag)

Case 2:

I took a number 1234

the code:

$number = 1234 //number 1234
$number = number_format($number, 0, '', ','); //add a thousand seprator
$number = str_pad($number,3,0,STR_PAD_LEFT); //pad if length less than 3
$counter = "";
foreach (str_split($number) as $key => $digit) {
    $counter .= '<b>' . $digit . '</b>';
}

Output: 1,234 (ignoring the <b> tag)

Case 3:

I took a number 0012

the code:

$number = 0012 //number 0012
$number = number_format($number, 0, '', ','); //add a thousand seprator
$number = str_pad($number,3,0,STR_PAD_LEFT); //pad if length less than 3
$counter = "";
foreach (str_split($number) as $key => $digit) {
    $counter .= '<b>' . $digit . '</b>';
}

Output: 010 (ignoring the <b> tag)


So what went wrong in case 3?

Update:

How to avoid this?

È stato utile?

Soluzione

The answer is, because octal:

$number = 0012;

The 0 prefix causes PHP to transform 12 using octal to decimal conversion; and 12 octal == 10 decimal.

To avoid this you could use string values instead:

$number = '0012';

See also: Integer notation

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top