Add trailing zeros to an integer

Viewed 2437

I need to add n trailing zeros to an integer.

For example:

n=4
y=1
output 10000

I used the code below but I need to give an integer value in place of n and that should be converted to number of zeros. Any idea?

n=00 
y=1 
printf  "%d$n\n" $y
3 Answers

I'm not sure what language you're using (I added the C++ tag just to get you going somewhere and get some views). But you might be best off to create a string (adding a 0 to the end of it for each iteration of the n variable). Then you could parse that string back to a number?

Otherwise, you could try multiplying your number by 10 for each n iteration.

Something like..

number = y

for (i = 0; i <= n; i++) {
    number *= 10;
}

You need to check whether n is greater than zero:

n=4
y=15
if [ $n -gt 0 ]; then
  printf  "$y%0*d\n" $n 0
else
  printf  "$y\n"
fi

Based on hutheano's answer, here is equivalent code in C:

#include <stdio.h>

int main()
{
  int n,y;
  n=4;
  y=1;

  if (n>0)
    printf("%d%0*d\n", y, n, 0);
  else
    printf("%d\n", y);

  return 0;
}
Related