Fill string with zeros on the left

Asked

Viewed 13,854 times

10

I’m doing a work of Operating Systems and need to turn decimal numbers into binaries. So far so good, because the method below takes an integer and converts to binary. My problem is the following:

When I put, for example (integer 1), it returns me correctly 1. But I have a stored value that would be the number of digits, for example (Qtd = 4). I would like the string to appear this way: 0001 with four digits.

It would be possible in this method to perform this procedure, regardless of the value of the variable number of digits?

public String converteDecimalParaBinario(int valor) {
   int resto = -1;
   StringBuilder sb = new StringBuilder();

   if (valor == 0) {
      return "0";
   }

   // enquanto o resultado da divisão por 2 for maior que 0 adiciona o resto ao início da String de retorno
   while (valor > 0) {
      resto = valor % 2;
      valor = valor / 2;
      sb.insert(0, resto);
   }

   return sb.toString();
} 

3 answers

15

You can use the Decimalformat class to format its output value. So:

    //coloque isso no final do seu método converteDecimalParaBinario
    DecimalFormat df = new DecimalFormat("0000");
    return df.format(Integer.parseInt(sb.toString()));

You say in the statement that you have a variable qtd which indicates the number of digits that must possess the output, so the construction of your Decimalformat object must be variable according to that quantity. To make this variable amount of digits, you can make a for and build your Pattern. Example:

    int qtd = 5;
    StringBuilder pattern = new StringBuilder();
    for(int i=0; i<qtd; i++) {
        pattern.append("0");
    }
    DecimalFormat df = new DecimalFormat(pattern.toString());

If it is not part of your job to convert the number to binary you can also use the method toBinaryString() from the Integer class to do the conversion for you. Example:

import java.text.DecimalFormat;
public class Bin {
    public static void main(String[] args) {
        System.out.println(converteDecimalParaBinario(4));
    }
    public static String converteDecimalParaBinario(int valor) {
        int qtd = 5;
        StringBuilder pattern = new StringBuilder();
        for(int i=0; i<qtd; i++) {
            pattern.append("0");
        }
        DecimalFormat df = new DecimalFormat(pattern.toString());
        return df.format(Integer.parseInt(Integer.toBinaryString(valor)));
    } 
}

Exit:

00100

To change the number of digits the output will have, simply change the variable value qtd.

  • 2

    +1 for making the API work for you instead of reinventing the wheel.

  • Thanks for the answers, but I already got it with the @Joannis proposal

  • 1

    @Rodrigosegatto, here at Stack we thank with positive votes ;)

9

You can perform as follows if it is a string:

String str = "123";
String formatted = ("0000" + str).substring(str.length());

Note: Enter a zero for each desired digit, that is, 4 digits you mention in the question lack 4 zeros.

Or if it’s a number:

Int number = 123;
String formatted = String.format("%04d", number);

Note: $04d is for picture digits, $05d is for 5 digits, etc...

Anyway, the second option is always better: have the variable with the correct type and format the number as intended by making use of the method format.


For your particular case, you could do it as follows:

String formatado = String.format("%04d", Integer.parseInt(sb.toString()));
return formatado;

Example

/* package superBuBu; */

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        int valor = 1;
        int resto = -1;

        StringBuilder sb = new StringBuilder();

        if (valor == 0) {
            System.out.println("0");
        }

        // enquanto o resultado da divisão por 2 for maior que 0 adiciona o resto ao início da String de retorno
        while (valor > 0) {
            resto = valor % 2;
            valor = valor / 2;
            sb.insert(0, resto);
        }

        String formatado = String.format("%04d", Integer.parseInt(sb.toString()));

        System.out.println(formatado);
    }
}

Example working on Ideone.

  • I could not understand where I put it in my method to return me what I need: Qtd=4; value = 2; String Returns in the method: '10' I want it to return '0010'

  • @Zuul notice that AP talks about the variable Qtd of digits that the output should have. Your code displays 4 digits always. It took me a while to figure that out, too, but I fixed it ;)

  • Thanks for the answers, but I already got it with the @Joannis proposal

  • @Math Will be? The question does not seem to convey that. The answer accepted despite using more code and cycles, ends up returning 4 digits... or I’m reading this all wrong?

  • @Zuul is that I was not trying to understand the accepted answer because I found it confusing. But reading the AP comment in his answer and this excerpt from the question "But I have a stored value that would be the number of digits (Qtd = 4)" I understood that. It’s very confusing, but that’s what I understood.

  • 1

    Ah yes, len<4 and len++ within the method makes the output always have 4 digits. Anyway... if the AP says the problem solved then is solved.

  • 2

    @Math Anyway, the problem of OP is outdated, I will keep my answer because it seems correct within my understanding of the problem. I recommend you do the same! In the future, with our peer review (Peer review) the thing ends up being tuned :)

  • IS < unrivalled @Math because if length==4 cannot enter the cycle. The author wanted a variable number of digits: "...independent of the value of the quantity variable.". And the answer considered to be right was that, at the time, it was better to answer the question in my view.

Show 3 more comments

7


Dude I didn’t test but this should work!

public String converteDecimalParaBinario(int valor) {
   int resto = -1;
   StringBuilder sb = new StringBuilder();
   int len=0;   

   if (valor == 0) {
      return "0000";
   }

   // enquanto o resultado da divisão por 2 for maior que 0 adiciona o resto ao início da String de retorno
   while (valor > 0) {
      resto = valor % 2;
      valor = valor / 2;
      sb.insert(0, resto);
   }
   len = sd.length();
   while(len<4){
       sd="0"+sd;
       len++;
   }
   return sb.toString();
} 

What I did:

I started a variable of type int calling for lenand assigns the size of the sd for len with the command len = sd.length();.
If len is less than 4 adds 0 left, repeats until Len is equal to 4. sd returns.

  • 1

    It worked! : D I just switched to turn Stringbuilder to String.

  • Coming back to this issue, it was just an incorrect thing @Joannis... When the whole is 0 it prints 0 when using the 4 boxes and printing this 0000. How to get the 4 zeros?

  • it returns 0 so if (value == 0) { Return "0"; } change to this: if (value == 0) { Return "0000"; ; }

  • Okay. It worked :D Thank you, you didn’t call me on this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.