In php questo è quello che ho fatto (ispirato da questo post). Forse non il più elegante, ma ... Ho creato una funzione per stampare numeri come stringhe. Volevo essere in grado di avere flessibilità, quindi ho un paio di parametri.
PHP:
function print_num($num,$numdec,$atleast = false,$max_dec = -1)
{
$ret_norm = false;
if (!$atleast)
$ret_norm = true;
else //atleast = true
{
//Want at least $numdec decimals
//Do we have two or fewer and want to return two or fewer?
if ($num == ((int)($num*100)/100) & $numdec <= 2)
$ret_norm = true;
else
{
//See if we have enough dec. already
$just_dec = substr((string)$num,strpos((string)$num,".") + 1);
if ($numdec >= strlen($just_dec))
$ret_norm = true;
else
{
//More decimals than at least value - make sure we don't go over max if set
if ($max_dec >= 0 && strlen($just_dec) > $max_dec)
{
//Confine to max_dec length
$ret_norm = true;
$numdec = $max_dec; //Set for sprintf below
$num = number_format($num,$max_dec); //Round the value so doesn't just chop off
}
else if ($max_dec >= 0)
$ret_norm = false;
} //else
} //else
} //else atlest
if ($ret_norm)
return sprintf("%0.".$numdec."f",$num);
else
return sprintf("%s",$num); //print as is
} //print_num
E per chiamare la funzione (per avere almeno due decimali, ma max 4:
print_num($mynum,2,true,4);
Se il numero è 34.1, si ottiene 34,10
Se il numero è 34.12345 ottieni 34.1235
ecc.
fonte
2016-03-30 19:40:59
L'argomento riguarda la formattazione. Non arrotondare. Inoltre, 'toFixed' ha la reputazione di essere selvaggiamente incoerente sul fatto che giri in su o in giù. – Kafoso
La differenza tra la formattazione e l'arrotondamento sembra semantica quando la domanda riguarda il valore di formattazione per un determinato numero di posizioni decimali. Se hai delle specifiche sull'incoerenza di 'toFixed 'potrebbe essere un'utile aggiunta. – SimplGy