note 107492 modified in function.number-format by danbrown

From: Date: Thu, 10 May 2012 20:56:59 +0000
Subject: note 107492 modified in function.number-format by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187851@lists.php.net to get a copy of this message
I was looking for a way to format a number to a certain number of significant digits, instead of decimal points.

This is what I came up with:

<?php
function number_significant($x, $n) {
 $x_sci = sprintf("%.".$n."e", $x); 
 $x_f = rtrim(sprintf("%f", $x_sci),"0");
 if ( $x_f[strlen($x_f)-1]=="." ) {
 $x_f .= "0";
 }
 return $x_f;
}
?> --was-- I was looking for a way to format a number to a certain number of significant digits, instead of decimal points. This is what I came up with: function number_significant($x, $n) { $x_sci = sprintf("%.".$n."e", $x); $x_f = rtrim(sprintf("%f", $x_sci),"0"); if ( $x_f[strlen($x_f)-1]=="." ) { $x_f .= "0"; } return $x_f; } http://php.net/manual/en/function.number-format.php

« previous php.notes (#187851) next »