Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

numbers - Round to max thousand, hundred etc in PHP

I have a pretty simple PHP question but I'm not sure how to do that.

I want to round to the max hundred or thousand depending on the value returned by the database.

Here are a few examples of what I need :

  • DB returns the value 11, I want PHP to output 20
  • DB returns the value 104, I want PHP to output 200
  • DB returns the value 1404, I want PHP to output 2000
  • DB returns the value 10241, I want PHP to output 11000

etc etc

I would like to create an automatic function to do that, according to the value passed.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Final implementation, inspired from Shaunkak's answer and SO's comment. Thanks for these bra..s. live demo

<?php
  $val = 10241.67;
  if($val >= 1000) {
    echo ceil($val / 1000) * 1000;
  }
  else {
    $length = strlen(ceil($val));
    $times = str_pad('1', $length, "0");
    echo ceil($val / $times) * $times;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...