macintosh264
macintosh264

Reputation: 981

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.

Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.

Upvotes: 0

Views: 2232

Answers (5)

Md. Saidur Rahman Milon
Md. Saidur Rahman Milon

Reputation: 2911

Using preg_match just get the zero ending with and then rtim it

<?php 
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
    echo rtrim($nn,$number[0]);
}

Hope it will help you.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96326

This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.

$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
    if (substr($s, -1) == '0')
        $s = substr($s, 0, -1);
}
print "Number = $s";

Upvotes: 7

Check the number format function:

<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>

http://php.net/manual/en/function.number-format.php

Upvotes: 0

Hammerite
Hammerite

Reputation: 22350

I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.

But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:

$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
    chop off last character of $mystring;
}

Upvotes: 0

CanSpice
CanSpice

Reputation: 35828

Use sprintf() to format a number to a certain number of decimal places:

$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);

Upvotes: 0

Related Questions