From 6e81c704467ce663d6fb48f5e7b8d453b78a69f2 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 7 Jan 2022 11:27:48 -0500 Subject: [PATCH] Fix issue processwire/processwire-issues#1502 --- wire/core/Sanitizer.php | 27 ++++++++++++++++--- .../modules/Inputfield/InputfieldFloat.module | 5 ++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/wire/core/Sanitizer.php b/wire/core/Sanitizer.php index 7ab1c46b..e54b9a72 100644 --- a/wire/core/Sanitizer.php +++ b/wire/core/Sanitizer.php @@ -3913,10 +3913,24 @@ class Sanitizer extends Wire { $str = trim($value); $prepend = ''; - if(strpos($str, '-') === 0) { + $append = ''; + + $c = substr($str, 0, 1); + while($c !== '' && $c !== '-' && $c !== '.' && $c !== ',' && !ctype_digit($c)) { + // trim off leading non-number content like currency symbols, names, etc. + $str = ltrim($str, $c); + $c = substr($str, 0, 1); + } + + if($c === '-') { $prepend = '-'; $str = ltrim($str, '-'); } + + if(stripos($str, 'E-') && preg_match('/^([0-9., ]+\d)(E\-\d+)/i', $str, $m)) { + $str = $m[1]; + $append = $m[2]; + } if(!strlen($str)) return $options['blankValue']; @@ -3959,7 +3973,7 @@ class Sanitizer extends Wire { preg_replace('/[^0-9]/', '', substr($str, $pos + 1)); } - $value = $prepend . $value; + $value = $prepend . $value . $append; if(!$options['getString']) $value = floatval($value); } @@ -3967,7 +3981,14 @@ class Sanitizer extends Wire { if(!is_null($options['min']) && ((float) $value) < ((float) $options['min'])) $value = $options['min']; if(!is_null($options['max']) && ((float) $value) > ((float) $options['max'])) $value = $options['max']; if(!is_null($options['precision'])) $value = round((float) $value, (int) $options['precision'], (int) $options['mode']); - if($options['getString']) $value = "$value"; + + if($options['getString']) { + if($options['precision'] === null) { + $value = strpos($value, 'E-') ? rtrim(sprintf('%.20f', (float) $value), '0') : "$value"; + } else { + $value = sprintf('%.' . $options['precision'] . 'f', (float) $value); + } + } return $value; } diff --git a/wire/modules/Inputfield/InputfieldFloat.module b/wire/modules/Inputfield/InputfieldFloat.module index 93979a21..84cb3fc2 100644 --- a/wire/modules/Inputfield/InputfieldFloat.module +++ b/wire/modules/Inputfield/InputfieldFloat.module @@ -117,6 +117,11 @@ class InputfieldFloat extends InputfieldInteger { $attributes['step'] = '.' . ($precision > 1 ? str_repeat('0', $precision - 1) : '') . '1'; } } + if($attributes && isset($attributes['value']) && strpos($attributes['value'], 'E-')) { + $attributes['value'] = $this->wire()->sanitizer->float($attributes['value'], array( + 'getString' => true, + )); + } return parent::getAttributesString($attributes); }