Page 1 of 1

Remove .0 from decimal numbers

Posted: Sun Oct 31, 2010 3:25 pm
by bradlc
How can I remove .0 from numbers?

I currently have output looking like this 64.0 x 31.0 x 35.3 cm, which is not very nice. I would like it outputted as 64 x 31 x 35.3 cm

This is the current code:

Code: Select all

$product_size = "";
$product_size .= number_format($this->data[0]->product_length,'1','.',',');
$product_size .= ' x ';
$product_size .= number_format($this->data[0]->product_width,'1','.',',');
$product_size .= ' x ';
$product_size .= number_format($this->data[0]->product_height,'1','.',',');
$product_size .= ' cm';

$this->template = str_replace('{product_size}',$product_size,$this->template);

Re: Remove .0 from decimal numbers

Posted: Sun Oct 31, 2010 4:16 pm
by internet-solution
Check if a value is an integer; and if yes, then round it up to integers.

Code: Select all

if($this->data[0]->product_length==(int)$this->data[0]->product_length)
$product_size .= number_format($this->data[0]->product_length);
else
$product_size .= number_format($this->data[0]->product_length,'1','.',',');
I prefer 64.0 x 31.0 x 35.3 cm, though - the decimal points are consistent in all three values.

Re: Remove .0 from decimal numbers

Posted: Sun Oct 31, 2010 4:29 pm
by greyhoundcode
Similar approach to internet-solution but using a function ...

Code: Select all

/**
 * If $number is a "whole" number then a string representing
 * the integer is returned, otherwise it is formatted to show a 
 * single decimal point.
 */
function Smart_Number_Format($number)
{
	if ( ((int) $number) == $number)
		return (string) ((int) $number);
	
	else
		return number_format($number, 1, '.', ',');
}

// Our array of numbers...
$data = array(30, 	27.642, 29.000);

// Output the string representation
echo Smart_Number_Format($data[0]) 
	. ' x ' 
	. Smart_Number_Format($data[1])
	. ' x '
	. Smart_Number_Format($data[2])
	. ' cm';

Re: Remove .0 from decimal numbers

Posted: Sun Oct 31, 2010 4:30 pm
by twinedev
I agree with keeping the .0, more consistent, but as to the solution, here is another method:

Code: Select all

str_replace('.0','',number_format($this->data[0]->product_length,'1','.',','))

Re: Remove .0 from decimal numbers

Posted: Sun Oct 31, 2010 5:12 pm
by greyhoundcode
Some very unscientific benchmarking with microtime() suggests there may not be much of a performance gap between either approach.

(How bored am I?)

Re: Remove .0 from decimal numbers

Posted: Mon Nov 01, 2010 12:05 am
by bradlc
I hear what you are saying about the consistent look, but I'm into reducing visual clutter.

I went with twinedev's approach - it works perfectly thanks :D