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
https://forums.phpfreaks.com/topic/223030-number-formats/
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
https://forums.phpfreaks.com/topic/223030-number-formats/#findComment-1153129
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
https://forums.phpfreaks.com/topic/223030-number-formats/#findComment-1153147
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
https://forums.phpfreaks.com/topic/223030-number-formats/#findComment-1153156
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.