Search code examples
stringtype-conversionnumbers

Convert string to number, respecting dots and commas for ordering


I need to order some products that are registered by users, based on their price.

I'm using WordPress and when the user ads a product, I get the field via input=text, then convert it with a function.

Unfortunately, the field that receives the converted number is also a text field and I can't change that.

So, I used the same function to convert the number when I loop the posts and get their content.

As far as visual goes, it works perfectly... But when I try to order by the price... It gets messed up.

Here is the function I have:

//convert the number which is a string, to float
function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : 
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    } 

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}
$value = get_field('preco_anuncio');
$precoFinal = tofloat($value);

Any ideas how to solve that? I need to preserve the 'visual' with dots and commas. Like: 3.567,00 €


Solution

  • Ok, so I got it to work. Don't know if it's the right way or the best way... But it solved my problem and I don't see any problem with it.

    Here is what I did:

    1. The input I have is a text input.

    2. I used JavaScript to visually make it look more like a currency field.

    3. When registering into the database, I convert it with the function toFloat that I posted:

      function tofloat($num) {
          $dotPos = strrpos($num, '.');
          $commaPos = strrpos($num, ',');
          $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : 
          ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
          if (!$sep) {
              return floatval(preg_replace("/[^0-9]/", "", $num));
      } 
      
      return floatval(
          preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
          preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
      );
      }
      
    4. Then I use the number_format() to remove any dots or spaces:

      number_format($precoAd, 2, ',', '');

    5. When I get the value back from the database, I pass it again to number_format() so it will look as I need:

      number_format($value, 2, ',', '.');