From c4dd739d7c6de8cb6bbf3333421af197c74e3887 Mon Sep 17 00:00:00 2001 From: David van der Tuijn Date: Thu, 31 Mar 2022 09:20:50 +0200 Subject: [PATCH] Added support for thousands (string with 3 decimals). --- README.md | 4 ++++ src/number_format_to_decimal.php | 28 ++++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ce9fe9d..d71c666 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ number_format_to_decimal('1000,99'); // 1000.99 number_format_to_decimal('1000.99'); // 1000.99 number_format_to_decimal('1.000,99'); // 1000.99 number_format_to_decimal('1,000.99'); // 1000.99 +number_format_to_decimal('10.000'); // 10000 +number_format_to_decimal('100.000'); // 100000 +number_format_to_decimal('10,000'); // 10000 +number_format_to_decimal('100,000'); // 100000 number_format_to_decimal('1.000.000'); // 1000000 number_format_to_decimal('1.000.000,99'); // 1000000.99 number_format_to_decimal('1,000,000'); // 1000000 diff --git a/src/number_format_to_decimal.php b/src/number_format_to_decimal.php index d9e4890..6843b34 100644 --- a/src/number_format_to_decimal.php +++ b/src/number_format_to_decimal.php @@ -28,16 +28,36 @@ function number_format_to_decimal(?string $value) $countDotSeperators += substr_count($value, '.'); } - // If there is one separator, and it is a comma, we replace the comma with a period. + // If there is one separator, and it is a comma. if ($countCommaSeperators == 1 && $countDotSeperators == 0) { - $decimal = str_replace(',', '.', $value); + $countDecimals = strlen(substr($value, strpos($value, ",") + 1)); + + // If there are 3 decimal places, we can assume that it is a thousand. + + if ($countDecimals == 3) { + // Remove the comma. + $decimal = str_replace(',', '', $value); + } else { + // Replace the comma with a period. + $decimal = str_replace(',', '.', $value); + } } - // If there's one separator, and it's a dot, we don't do anything. + // If there's one separator, and it's a dot. elseif ($countCommaSeperators == 0 && $countDotSeperators == 1) { - $decimal = $value; + $countDecimals = strlen(substr($value, strpos($value, ".") + 1)); + + // If there are 3 decimal places, we can assume that it is a thousand. + + if ($countDecimals == 3) { + // We remove the period. + $decimal = str_replace('.', '', $value); + } else { + // Do Noting + $decimal = $value; + } } // If there are two different separators.