3

Help me, how to add a significant 0 to number variable (int, float, ecc)?

int s = 0; -> 00
int m = 0; -> 00
int h = 0; -> 00
HAL9000
  • 3,562
  • 3
  • 25
  • 47
Matrix
  • 31
  • 1

5 Answers5

8

You can't add significant 0's to numbers; that is an aspect of how they are DISPLAYED, not the values themselves.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
2

You can't. However, you can change the way it's displayed, use String#format:

String res = String.format("%02d", s);
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

This doesn't mather when you do calculations. But another way of doing this would be:

int s = 10;
System.out.println((s > 9)? s : "0" + s);
s = 0;
System.out.println((s > 9)? s : "0" + s);

Output:

> 10
> 00
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

You Can't do that.
Try

int v = 1;
String value = (v<=9)?"0"+v:v+"";
System.out.println(value);

OR
you can use String.format("%02d", v);

Output

01
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0

You could create a new class which contains an integer value and a number of significant zeros. Then you can override the toString() method in order to convert it to a string when you need to display it:

public class MyInteger{
    private int value;
    public int numOfZeros = 3; // default number of significant zeros
    public MyInteger(int val){
        this.value = val;
    }
    public String toString(){
        String format = new String("%0"+numOfZeros+"d");
        String s = new String(""+value);
        return String.format(format,s);
    }
}

In this way when you append this object to a string it will automagically converted in a string with the desired number of significant digits.

HAL9000
  • 3,562
  • 3
  • 25
  • 47