Home > Mobile >  Formatting a Census Tract String to xxxxx.xx
Formatting a Census Tract String to xxxxx.xx

Time:11-09

I am receiving a census track as "022100". The proper output should be 0221.00.

What is the best way to format this string in PHP? I guess I need it to remain as a string since it had a leading zero. I was originally thinking of multiplying it x .01 and then number formatting it, but that will remove the leading zero.

While substr_replace($response->tract_code, '.', 4, 0) works, I would prefer to rely on counting two positions from the right.

Thanks in advance.

CodePudding user response:

You can do something like this.

$str = "022100";
$offset = strlen($str)-2;
$newstr = substr_replace($str, ".", $offset, 0);

CodePudding user response:

Alternative solution with preg_replace().

$str = "022100";
$formatStr = preg_replace('/^(.*)(..)$/u','$1.$2',$str);
//string(7) "0221.00"
  •  Tags:  
  • php
  • Related