PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to round number to 10, 100, 1000, 10000, 100000

 October 17, 2022     integer, python     No comments   

Issue

I want a function that will round the number to 10 if it is less than 10, round to 100 if it is between 10 to 1000 and so on.

this will help number concatenation problems, so I don't have to turn number to str and back.

def roundup(n):
    if n < 0: return 0
    if n < 10: return 10
    if n < 100: return 100
    if n < 1000: return 1000
    if n < 10000: return 10000

I want to know if there is a natural way to do this without just stacking 'if's together


Solution

You could use the naive approach:

def roundup(n):
    top = 1
    while True:
        if n <= top:
            return top
        top *= 10

You would need top = 1L in Python2, but integers are long by default in Python3.



Answered By - Serge Ballesta
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing