Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...