All pastes #940973 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-03-13 12:54 UTC
rendered paste body
<?php
$testNumbers = array("123.123,12",
                    "123.123.123,12",
                    "123,123.12",
                    "123,123,123.12",
                    "123,123,123",
                    "123,123",
                    "123.123.123",
                    "123.123",
                    "123",
                    "12",
                    "123.1",
                    "123,1",
                    "12,1234"
                    );

function fixDecimals($testNumber,$decimals=2) {
  $chunks = preg_split("/[\s\.,]+/",$testNumber);
  
  $numChunks = count($chunks);
  $lastChunk = $numChunks-1;
  
  if ($numChunks == 1) {
    return $testNumber;
  }
  
  if (strlen($chunks[$lastChunk]) > $decimals) {
    return implode("",$chunks);
  }
  
  if (strlen($chunks[$lastChunk]) <= $decimals) {
    for($i=0;$i<$lastChunk;$i++) {
      $out = $out.$chunks[$i];
    }
    $out = $out.".".$chunks[$lastChunk];
    return $out;
  }
}
echo '<pre>';
foreach ($testNumbers as $testNumber) {
  echo fixDecimals($testNumber,2)."\n";   
}
echo '</pre>';
?>