Home > Software design >  Can't figure out how to convert decimal to percentage properly
Can't figure out how to convert decimal to percentage properly

Time:11-05

I have this number 0.00072731252499793 and I need to convert it to a percentage value so it returns the result of 72% but I cannot figure out the way to do it. I tried some solutions from another threads but no luck. I always got 0%. Is there any way to achieve this?

my code

<?php

$number = 0.00072731252499793;
echo round( $number * 100 ) . '%'; // this gave me 0%

CodePudding user response:

Assuming 1 means 100%, then 0.00072731252499793 is 0.07..% so when you round it it becomes zero, because default rounding rule is PHP_ROUND_HALF_UP, and default precision (numbers after comma) is 0

https://www.php.net/manual/en/function.round.php

Depending on your needs, you can try to adjust precision like this

<?php

$number = 0.00072731252499793;
echo round( $number * 100, 2 ) . '%'; // 0.07%

CodePudding user response:

If you want to convert 0.00072731252499793 to 72, you need to multiply it with 100000 and after that round it down (floor).

so you can use:

<?php
$number = 0.00072731252499793;
echo floor($number * 100000) . '%';

What you are doing is : You're multiplying 0.00072731252499793 with 100 which returns 0.072731252499793 and round function is converting it into 0 as you're not passing any decimal place.

CodePudding user response:

Try this:

<?php

$number = 0.00072731252499793;
echo round( $number * 100000 ) . '%'; 
  •  Tags:  
  • php
  • Related