-1

Is there any way to do a regex that cuts off a number at a certain point without rounding (simply drops the digits?) say after 4 digits.... It will not be handling negative numbers, EVER. I could have number inputs such as 0.03123 or 1.31, or 10000.98, etc .... What I have written so far as my solution is rounding and not what I'm seeking....

$number = 10000.51999999;
$precision = 4;
echo "<br>";

// grab number before decimal by rounding down the whole number down...
$numberBeforeDecimal = floor($number); 
echo "<br>";

// grab the decimal and set the correct precision needed
$n = $number;
intval($n); // 12
$theDecimalPart = explode('.', number_format($n, ($precision)))[1]; // 3430

echo $theDecimalPart; // this is outputting 5200

$theNewValue = $numberBeforeDecimal.".".$theDecimalPart;
MrChemical
  • 25
  • 5
  • 2
    Yes, you could even just do it with http://php.net/manual/en/function.substr.php Something like `\d+\.\d{1,4}` would give you a float with 1-4 decimal places. – user3783243 Oct 07 '18 at 18:49
  • 1
    `$output = floor($input * 100) / 100;` – Spudley Oct 07 '18 at 19:15
  • Don't use regex for this. But if you *must* use regex, it would look like this: `preg_match("~^\d+\.\d\d~", "123.4567", $matches);` – Spudley Oct 07 '18 at 19:16
  • And you seem unaware of PHP's `number_format()` function. It isn't an answer for you as it does rounding, but it would replace all the work in the code you've written in the question with a single line of code. – Spudley Oct 07 '18 at 19:18

1 Answers1

1
  • explode() the number to get integer and decimal part separated out in an array
  • Use substr() function to get relevant precision from the decimal part.
  • Finally, concatenate them back.

Try the following (Rextester DEMO):

$number = 10000.51999999;
$precision = 4;

// separate out the integer and decimal part
$number_str_arr = explode('.', $number);

// concatenate them back
$theNewValue = $number_str_arr[0] . '.' . substr($number_str_arr[1], 0, $precision);
echo $theNewValue; // displays 10000.5199
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57