Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 266
  • Last Modified:

Preg_Replace Help

I am using a number which can have up to 8 decimal places.  However this number is actually currency so i would like it to display clearly.

I need to make sure i have no less than 2 decimal places but display anywhere up to 8.

For example i need these numbers to display these results:

0.2 = 0.20
0.1 = 0.1
0.15 = 0.15
0.156800 = 0.156800
0.268 = 0.268
1.95660010 = 1.9566001

I am currently using this code which works fine but it will not leave me with 2 decimal places if the last number is a 0.

      $longDecimal = number_format($old_number, 8, '.', '');
      $number = preg_replace('/\.?0+$/', '', $longDecimal);

Does anybody no the preg_replace pattern for only replacing chars after 2 decimal places??
0
Sailo100
Asked:
Sailo100
  • 3
  • 3
1 Solution
 
cg_medistoxCommented:
Try using the number format function built into php?

http://uk3.php.net/number_format
0
 
Sailo100Author Commented:
I don't want to round the number to 2 decimal places..... i just don't want to display the trailing zeros except for the first 2 after the decimal place.
0
 
cg_medistoxCommented:
You can stipulate how many decimals you would like the function to work to
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Sailo100Author Commented:
Pleasde provide me with the code that will do what i have requested above?
0
 
cg_medistoxCommented:
OK, good point, you get trailing zero's.

My bad
0
 
jasonsbytesCommented:
<?php

$old_number = '0.2';

$longDecimal = number_format($old_number, 8, '.', '');
$number = preg_replace('/\.?0+$/', '', $longDecimal);
$number = preg_replace('/^(\d+\.\d)$/', '${1}0', $number);

print $number;
print "\n";

?>
0
 
Sailo100Author Commented:
Perfect!
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now