Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/795087da77d016432b96e51ad850ae92 to your computer and use it in GitHub Desktop.
Save yavgel85/795087da77d016432b96e51ad850ae92 to your computer and use it in GitHub Desktop.
Truncate Number #php
<?php
// Truncate Number without rounding the value
function truncate_number($number, $precision = 2)
{
// Zero causes issues, and no need to truncate
if (0 == (int) $number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure returns correctly negative / positive
return floor($number * $precision) / $precision * $negative;
}
// https://stackoverflow.com/questions/9944001/delete-digits-after-two-decimal-points-without-rounding-the-value/9944052
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment