Created
March 26, 2021 08:40
-
-
Save yavgel85/795087da77d016432b96e51ad850ae92 to your computer and use it in GitHub Desktop.
Truncate Number #php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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