Jump to content

Number Formats


Rommeo

Recommended Posts

I m printing the prices of the items in my db.

I want to print the prices like ;

 

Price --- The format I want

75.000 --- 75

75.500 --- 75.5

100 --- 100

100.5 --- 100.5

1234.654 --- 1,234.654

1234.200 --- 1,234.2

1123456.789 --- 1,123,456.789

 

Simply I want to cancel the zeros after dot, and want to put comma every 3 digits before the dot. How can I do this ?

 

Link to comment
Share on other sites

There is probably an easier way but this will at least get you started:

 

$arr = array(75.000, 75.500, 100, 100.5, 1234.654, 1234.200, 1123456.789);
foreach($arr as $key => $value)
{
   echo rtrim(number_format($value, 4), '0') . "\n";
}


?>

Link to comment
Share on other sites

This should do what you want:

$nums = array(75.000,75.500,100,100.5,1234.567,1234.200,1123456.789);
foreach ($nums as $num) {
    echo rtrim(rtrim(number_format($num,3),'0'),'.') . "\n";
}
?>

 

 

Just curious as to why you have '.' in your charlist for the rtrim parameter?

Ken

Link to comment
Share on other sites

If you are interested in another alternative, I just pooped this one out:

(does allow for more control)

<?php

/*GHETTO NUMBER FORMATTER v1.0*/

//Define your number
$number = '12865.25000';

//Split number at the .(decimal)
$number = explode('.', $number);

//Define the whole number
$whole = $number[0];

//Format the whole number
$whole = number_format($whole, 0,'', ',');

//Define the decimal
$decimal = $number[1];

//Format the decimal
$decimal = rtrim($decimal, '0');

if($decimal != ''){
	//Concatonate the Whole number and Decimal back together
	$number = $whole.'.'.$decimal;
}else{
	//Just return the whole number
	$number = $whole;
}
//Echo result
echo $number;

?>

Link to comment
Share on other sites

I like the title, but that's a little overboard to simply format a number.

 

I had started with a simpler variation on the number_format() and for some reason once it got into larger number, billions, etc... It was doing some wierd rounding. Perhaps there was a better fix, but this one has worked so far.

 

Do you know a more lightweight way to bypass the rounding in the number_format() ??

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.