Last active
April 14, 2021 12:28
-
-
Save mean-cj/e28f5a527fe64a1c23510eade7f494ab to your computer and use it in GitHub Desktop.
Javascript/PHP numberFormat not round
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 | |
// numberFormat not round, PHP Version | |
// https://stackoverflow.com/questions/3833137 | |
public static function numberFormatNoRound($number, $decimals = 2, $decPoint = '.', $thousandsSep = ',') | |
{ | |
$negation = $number < 0 ? -1 : 1; | |
$coefficient = pow(10, $decimals); | |
$number = ($negation * floor((string) (abs($number) * $coefficient))) / $coefficient; | |
return number_format($number, $decimals, $decPoint, $thousandsSep); | |
} | |
?> | |
-------------------------------- | |
// numberFormat not round, Javascript Version | |
<script> | |
function numberFormatNoRound($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',') | |
{ | |
return number_format((Math.floor($number * 100) / 100).toFixed($decimals), $decimals, $decPoint, $thousandsSep ); | |
} | |
//https://locutus.io/php/strings/number_format/ | |
//https://www.cmdevhub.com/number_format/ | |
function number_format(number, decimals, decPoint, thousandsSep) { | |
if(decimals === 'undefined') decimals = 2; | |
number = (number + '').replace(/[^0-9+\-Ee.]/g, '') | |
const n = !isFinite(+number) ? 0 : +number | |
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals) | |
const sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep | |
const dec = (typeof decPoint === 'undefined') ? '.' : decPoint | |
let s = '' | |
const toFixedFix = function (n, prec) { | |
if (('' + n).indexOf('e') === -1) { | |
return +(Math.round(n + 'e+' + prec) + 'e-' + prec) | |
} else { | |
const arr = ('' + n).split('e') | |
let sig = '' | |
if (+arr[1] + prec > 0) { | |
sig = '+' | |
} | |
return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec) | |
} | |
} | |
// @todo: for IE parseFloat(0.55).toFixed(0) = 0; | |
s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.') | |
if (s[0].length > 3) { | |
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep) | |
} | |
if ((s[1] || '').length < prec) { | |
s[1] = s[1] || '' | |
s[1] += new Array(prec - s[1].length + 1).join('0') | |
} | |
return s.join(dec) | |
} | |
console.log(numberFormat(3000.79)); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment