Pick value after point

Asked

Viewed 1,403 times

1

Well I have the following variable.

$valor = "235.33333333333333";

I need to return the value with only 2 decimal places (235.33). How can I do this? Using the explode?

  • 1

    Seria that?

  • do not want to do any kind of formatting, just want to cut the fields after the stitch, and keep only 3 digits after ready.

  • 2

    It doesn’t make much sense you do this with explode, use the number_format function.

  • So resolve? $Padded = sprintf('%0.2f', $value);

2 answers

4


Using explode you can do so:

$valor = "235.33333333333333";

$s = explode('.' $valor);

$result = $s[0] . '.' . substr($s[1], 0, 2);

print_r($result); // 235.33

But I recommend you do with the number_format.

With number_format:

$valor = "235.33333333333333";

$result = number_format($valor, 2);

print_f($result); // 235.33

2

Another option would be to use the round.

$valor = "235.33333333333333";
echo round($valor, 2); #235.33
  • 1

    Just take care because the round serves to round up, and in some logics this can be a problem. If the number were 235.66666 for example it would show 235.67

Browser other questions tagged

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