3

I have a random number such as 35 127 3658 45782 etc... I want to round them to 10^ form like 10 100 1000 10000. I can do it with this code:

Math.pow(10, (int)(Math.log10(number)) + 1);

But this code seems to me a bit complex and long for basic operation like that. Is there a better way to do it?

  • 3
    I actually do not think there is a simpler way of doing so. You could count the number of places using String operations (like `Math.pow(10, String.valueOf(number).length())`) but I do not think that would be in any way more elegant or efficient. – Ben Jul 24 '18 at 10:00
  • 1
    [This](https://stackoverflow.com/a/1308407/9379617) answer suggests that it's probably faster to use a divide and conquer for the calculation of the number of places but I don't really think that's what you're looking for (calling that an elegant solution would be a stretch) – Ben Jul 24 '18 at 10:01
  • Possible duplicate of [Fastest way to find the largest power of 10 smaller than x](https://stackoverflow.com/questions/4513707/fastest-way-to-find-the-largest-power-of-10-smaller-than-x) – OmG Jul 24 '18 at 13:38
  • I think there is no other way than this that more elegant. But ty anyways – Furkan Atılgan Jul 25 '18 at 11:24
  • I think you should use BigDecimal if you want to get precision. Click the link if you want to learn more. https://www.geeksforgeeks.org/bigdecimal-class-java/ – Laser Infinite Jan 12 '20 at 15:18

1 Answers1

-2
float t =10,number;
//scan a value for "number"
while(number/t > 1)
{
t = t * 10;
}
if( (number/t) % 1 >= 0.5)
System.out.println(t);
else
System.out.println(t/10);

Though it takes more lines, this is simple to understand.

vinayak
  • 34
  • 8
  • 1
    This calculates the wrong result (e.g. for `214` you get `1000`) and also does not work for `number = 1`. Also you probably want to use a long instead of an int for `t` as the suggested input number is out of int range. – Ben Jul 24 '18 at 10:10
  • Sorry, I rounded it to the next 10^ number – vinayak Jul 24 '18 at 10:22