简体   繁体   中英

Adding leading zeros to number_format

i have problems adding a leading zero to a number_format() number:

$number = "6,0"; // coming as string from DB      
number_format((double)$number, 1, '', '')  

I need to get

  • 060 from 6,0 or
  • 150 from 15,0 or
  • 123 from 12,3 or
  • 012 from 1,2

Using

sprintf("%02d",$...); 

didn't help. Any other possibilities?

You'll need to get rid of the commas first:

$number = str_replace( ',', '', $number );

Then you can use str_pad as was suggested in this question , which Francesco Malatesta posted as a comment.

$number = str_pad( $number, 3, '0', STR_PAD_LEFT );

You can reduce it to a oneliner:

$number = str_pad( str_replace( ',', '', $number ), 3, '0', STR_PAD_LEFT );
str_replace(",",'',$number);

用这个

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM