Round up to nearest power of 10

和自甴很熟 提交于 2020-01-04 01:49:12

问题


I'm trying to figure out how to round up a number (greater than 0) to the nearest power of 10.

Examples:

roundUp(23.4) = 100
roundUp(2.34) = 10
roundUp(.234) = 1
roundUp(0.0234) = 0.1
roundUp(0.00234) = 0.01

For numbers greater than 1, I believe this works:

10^(ceil(log10(x)))

But for numbers between 0 and 1, I'm not sure how to arrive at the answer.


回答1:


Oops. I didn't realize the function actually DOES work for numbers between 0 & 1. It was a brain fart that I saw a negative number for log10(x) and just assumed I couldn't take 10^ of that.

Carry on.




回答2:


Divide by 10, take the ceiling, multiply by 10.

123 -> 12.3 -> 13 -> 130
4 -> 0.4 -> 1 -> 10

Edit: Ah, misunderstood your request. I didn't realise you wanted the nearest power of ten, both positive and negative.



来源:https://stackoverflow.com/questions/19870067/round-up-to-nearest-power-of-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!