Formatting PHP values

Asked

Viewed 59 times

0

I want to format a value that leaves the function rand() only it’s not the usual way. I have a rand():

<?php
$valor = rand(3000,7000);

echo number_format($valor, 2);
?>

Output: 5000,00

I need the output to be 50,00 and not 5000,00.

It had a code that the rand() would go with the "." (dot) being more or less like this

<?php
rand(30.00, 70.00)
?>

Only that it seemed that he made the draw with the first 2 values, from 30 to 70 and also need to take the cents, IE, It can be a draw that came out for example 41.32

  • you always want whole, that’s it?

  • @Marllonnasser no, I need some of the values after "." (point). That is, it can be 30.00 as well as 32.59 for example.

  • then what is the doubt? rs

  • I need the function rand() draw these kind of numbers. Not only integers, but completes. I have the minimum value 30.00 and the maximum 70.00 so Rand() has to draw values in this range and I want to return tb the cents.

1 answer

0


rand($min*10, $max*10)/10

That’s it?

<?php
echo rand(20*10,30*10)/10
?>

Output:

25.4

Edit:

<?php
function randomWithDecimal($min, $max, $decimal = 0) {
  $scale = pow(10, $decimal);
  return mt_rand($min * $scale, $max * $scale) / $scale;
}
echo randomWithDecimal(30, 70, 2);
?>

Output:

44.37
  • No friend, you still don’t understand my question rs. I have the minimum value 30.00 (thirty reais) and maximum 70.00 (seventy reais) with the Rand I want to draw a value between 30.00 and 70.00, I want the returned value to be type 64.23 (sixty reais and twenty three cents). I don’t want him to just return me 64.00, but the entire amount that is 64.23

  • I edited it. That’s it?

  • Absolutely! : ).. Solved!. You can explain to me only what you did with the function pow and mt_rand?

  • There is math... the pow is to take the exponential value of the number of decimal places you want. o mt_rand can be replaced by rand also. The move is to take the exponential and work on it. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.