Related
How can I convert a String such as "12.34" to a double in Java?
You can use Double.parseDouble() to convert a String to a double:
String text = "12.34"; // example String
double value = Double.parseDouble(text);
For your case it looks like you want:
double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());
If you have problems in parsing string to decimal values, you need to replace "," in the number to "."
String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );
To convert a string back into a double, try the following
String s = "10.1";
Double d = Double.parseDouble(s);
The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
Use new BigDecimal(string). This will guarantee proper calculation later.
As a rule of thumb - always use BigDecimal for sensitive calculations like money.
Example:
String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
You only need to parse String values using Double
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
Citing the quote from Robertiano above again - because this is by far the most versatile and localization adaptive version. It deserves a full post!
Another option:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
There is another way too.
Double temp = Double.valueOf(str);
number = temp.doubleValue();
Double is a class and "temp" is a variable.
"number" is the final number you are looking for.
This is what I would do
public static double convertToDouble(String temp){
String a = temp;
//replace all commas if present with no comma
String s = a.replaceAll(",","").trim();
// if there are any empty spaces also take it out.
String f = s.replaceAll(" ", "");
//now convert the string to double
double result = Double.parseDouble(f);
return result; // return the result
}
For example you input the String "4 55,63. 0 " the
output will the double number 45563.0
Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.
Guava offers a utility method for this which returns null in case your String can't be parsed.
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
In runtime, a malformed String input yields null assigned to valueDouble
Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ;
took all the cases for any string double with Eng:"Bader Qandeel"
public static double str2doubel(String str) {
double num = 0;
double num2 = 0;
int idForDot = str.indexOf('.');
boolean isNeg = false;
String st;
int start = 0;
int end = str.length();
if (idForDot != -1) {
st = str.substring(0, idForDot);
for (int i = str.length() - 1; i >= idForDot + 1; i--) {
num2 = (num2 + str.charAt(i) - '0') / 10;
}
} else {
st = str;
}
if (st.charAt(0) == '-') {
isNeg = true;
start++;
} else if (st.charAt(0) == '+') {
start++;
}
for (int i = start; i < st.length(); i++) {
if (st.charAt(i) == ',') {
continue;
}
num *= 10;
num += st.charAt(i) - '0';
}
num = num + num2;
if (isNeg) {
num = -1 * num;
}
return num;
}
String s = "12.34";
double num = Double.valueOf(s);
Try this,
BigDecimal bdVal = new BigDecimal(str);
If you want Double only then try
Double d = Double.valueOf(str);
System.out.println(String.format("%.3f", new BigDecimal(d)));
How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.
How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.
I am trying to convert a number from decimal value to its IEEE 752 form. For example:
+43.9542 -> 01000010001011111101000100011010
-43.9542 -> 11000010001011111101000100011010
And I have written this method:
public float GetFloat32(String numero) {
//Convert
int intBits = Integer.parseInt(numero, 2);
float myFloat = Float.intBitsToFloat(intBits);
//Exponent
getExponent = 127 + (String.valueOf(Integer.toBinaryString(Math.abs((int) myFloat))).length() - 1);
//Sign
getSign = (myFloat < 0) ? 1 : 0;
return myFloat;
}
There is a problem that I cannot solve. I will make another example to make it clear.
double a = k.GetFloat32("01000010001011111101000100011010")
a = 43.9542
But when the number is negative, such as
double a = k.GetFloat32("1000010001011111101000100011010")
I get this error:
It means that my code works perfectly with positive numbers (including the zero) but with negative numbers it crashes. Where is the problem?
Note
I thought that I could solve my problem in this way
Check if String numero has a charAt(0) equal at 1
If yes (numero.charAt(0) == 1) then remove the first char
Call GetFloat32() with the new number (without the 1)
Return the result adding the - in front of the num
This could work but I would like to know where is the problem in the method above. I'd prefer avoiding this solution if possible.
The problem is that int/Integer has an upper limit of 0x7FFF_FFFF and so the Integer.parseInt method won't go beyond this limit.
Use Long.parseLong, check the resulting value for exceeding 0x7FFF_FFFFL and handle according to the logic required for negative integer values.
Although, I don't see anything bad in your very own idea of stripping the sign bit and dealing with the rest to get the absolute value.
Edit There isn't a way to get the encoded float with a simple integer conversion from a bit string. Just consider that +1 and -1 in 32 binary digits according to two's complement representation differ in more than one bit, and 100....000 isn't -0. Signed magnitude isn't the same as two's complement. Moreover, Java's binary and hexadecimal (or any other base's) literals are meant to be positive quantities; if you need a negative value, use a sign.
Later Method Integer.parseUnsignedInt doesn't have an advantage over using Long, since you'll then have to know how use two's complement arithmetic to remove the leading (sign) bit to produce the absolute value which can then be split into exponent and mantissa. (Add or subtract Integer.MIN_VALUE.)
If there isn't IEEE 752 and IEEE 754 is the target format, the easiest form is
float f1 = Float.intBitsToFloat(Integer.parseUnsignedInt(numerio,2));
public class IEEE754ToFloatingValues {
public static double convertToInt(String mantissa_str) {
int power_count = -1;
double mantissa_int = 0.0;
for (int i = 0; i < mantissa_str.length(); i++) {
// System.out.print(Integer.parseInt(mantissa_str.charAt(i) + ""));
mantissa_int += (Integer.parseInt(mantissa_str.charAt(i) + "") * Math.pow(2, power_count));
power_count -= 1;
}
IEEE754ToFloatingValues.logger.info((Object) "IEEE754ToFloatingValues : convertToInt :: end");
return mantissa_int + 1.0;
}
public static String convertToBinary(int i) {
return Integer.toBinaryString(i + 0b10000).substring(1);
}
public static String decimalToHex(String decimal) {
int i = Integer.parseInt(decimal);
System.out.println("<<>>" + i);
String my_hexdata = Integer.toHexString(i);
System.out.println(my_hexdata);
return String.valueOf(ReturnFloatingValue(my_hexdata));
}
public static double ReturnFloatingValue(String my_hexdata) {
String myString = "";
if (my_hexdata == null) {
return -2.0;
}
if (my_hexdata.length() != 8) {
myString = String.format("%1$-" + 8 + "s", my_hexdata).replace(' ', '0');
System.out.println("My hex data after appending 0's is : " + myString);
}
String binary = "";
for (int i = 0; i < myString.length(); i++) {
int num = Integer.parseInt(myString.charAt(i) + "", 16);
binary += convertToBinary(num);
}
System.out.println("Binary length is : " + binary.length());
System.out.println("Binary number is : " + binary);
if (binary == null || binary.isEmpty()) {
return -3.0;
}
String ieee_32 = binary.substring(2);
ieee_32 = String.format("%1$-32s", binary).replace(' ', '0');
long sign_bit = Long.parseLong(new StringBuilder().append(ieee_32.charAt(0)).toString());
long exponent_bias = Long.parseLong(ieee_32.substring(1, 9), long exponent_unbias = exponent_bias - 127L;
System.out.println("Exponent unbias is : " + exponent_unbias);
String mantissa_str = ieee_32.substring(9);
double mantissa_int = convertToInt(mantissa_str);
double real_no = Math.pow(-1.0, (double) sign_bit) * mantissa_int * Math.pow(2.0, (double) exponent_unbias);
System.out.println("Real no is : " + real_no);
return real_no;
}
public static void main(String[] args) {
//decimalToHex("0");
}
}
import java.util.*;
public class IEEE754 {
public static void main(String[] args) {
float floa;
Scanner sc = new Scanner(System.in);
System.out.println("ENTER A FLOATING POINT NUMBER");
floa=sc.nextFloat();
int no,sign;
no=(int) floa;
String a= Integer.toBinaryString(no);
String sub=a.substring(1, a.length());
if(floa<0)
{
sign=1;
}
else
{
sign=0;
}
int exp=a.length()-1;
System.out.println(exp);
int be=127+exp;
String b= Integer.toBinaryString(be);
System.out.print("biased exponent->");
System.out.println(b);
int loop=23-exp;
float floatpart =floa-no;
int q[]=new int[25];
for(int i=1,j=0;i<=loop;i++,j++)
{
q[j]=(int) (floatpart*2);
floatpart=floatpart*2;
if(q[j]==1){
floatpart=floatpart-1;
}
}
System.out.print("mantissa->");
System.out.print(sub);
for(int k=0;k<q.length;k++)
System.out.print(q[k]);
System.out.println();
System.out.println("IEEE754 FORMAT IS");
System.out.print(sign+" "+b+" ");
System.out.print(sub);
for(int k=0;k<q.length;k++)
System.out.print(q[k]);
}
}
How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.