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
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
You can't add significant 0's to numbers; that is an aspect of how they are DISPLAYED, not the values themselves.
You can't. However, you can change the way it's displayed, use String#format
:
String res = String.format("%02d", s);
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
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
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.