Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding zeros in front of a string

I need your help.

I'd like to create a function that would add some zeros in front of a number. The maximum numbers of digits that the total string should have is 6. Here are examples:

     9 -> 000009
    14 -> 000014
   230 -> 000230
  1459 -> 001459
 21055 -> 021055
987632 -> 987632 (Do nothing, there's already 6 digits)
like image 648
BobbyJones Avatar asked May 27 '15 18:05

BobbyJones


People also ask

How do you add a leading zero to a double in Java?

Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .

How do you determine the number of zeros in a string?

Keep a sum variable initialized with value zero. Loop through the characters of string and take the sum of all the characters. The sum of all the characters of the string will be the number of 1's, and the number of zeroes will be the (length of string - number of 1's).

How do you make a string of zeros in Java?

There are two main ways to add zeros at the start of an integer number in Java, first by using format() method of String class, and second by using format() method of DecimalFormat class. String.


1 Answers

A simple one line solution without any loops

Works with IE5-11, Firefox, Chrome, etc. Assumes integer input.

 function pad(n) { return ("000000" + n).slice(-6); }

Run snippet to test:

<html>
<body>
<input id="stdin" placeholder="enter a number" maxlength="6"><button onclick="test()">Test</button>
<textarea id="stdout" style="width:100%;height:20em;padding:1em;"></textarea>
<script type="text/javascript">
    
   function pad(n) { return ("000000" + n).slice(-6); }
    
   function test() {
       var n = parseInt( document.getElementById('stdin').value);
       var e = document.getElementById('stdout').innerHTML += n + ' = ' + pad(n) + '\n';
   }
 
</script>
</body>
</html>
like image 138
Roberto Avatar answered Sep 23 '22 01:09

Roberto