How can I pad an integer with zeros on the left? - java

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.

Related

What is the safest way to complete String digits with zeros in Java? [duplicate]

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 to implement "String.format()" in Java? [duplicate]

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.

Convert decimal to IEEE Binary

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]);
}
}

Displaying Currency in Indian Numbering Format

I have a question about formatting the Rupee currency (Indian Rupee - INR).
Typically a value like 450500 is formatted and shown as 450,500. In India, the same value is displayed as 4,50,500
For example, numbers here are represented as:
1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
Refer Indian Numbering System
The separators are after two digits, except for the last set, which is in thousands.
I've searched on the internet and people have asked to use the locale en_GB or pattern #,##,##,##,##0.00
I tried this on JSTL by using the following tag:
<fmt:formatNumber value="${product.price}" type="currency"
pattern="#,##,##,##,###.00"/>
But this does not seem to solve the issue.
Unfortunately on standard Java SE DecimalFormat doesn't support variable-width groups. So it won't ever format the values exactly as you want to:
If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Most number formatting mechanisms in Java are based on that class and therefore inherit this flaw.
ICU4J (the Java version of the International Components for Unicode) provides a NumberFormat class that does support this formatting:
Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println(format.format(new BigDecimal("100000000")));
This code will produce this output:
Rs 10,00,00,000.00
Note: the com.ibm.icu.text.NumberFormat class does not extend the java.text.NumberFormat class (because it already extends an ICU-internal base class), it does however extend the java.text.Format class, which has the format(Object) method.
Note that the Android version of java.text.DecimalFormat class is implemented using ICU under the hood and does support the feature in the same way that the ICU class itself does (even though the summary incorrectly mentions that it's not supported).
With Android, this worked for me:
new DecimalFormat("##,##,##0").format(amount);
450500 gets formatted as 4,50,500
http://developer.android.com/reference/java/text/DecimalFormat.html - DecimalFormat supports two grouping sizes - the primary grouping size, and one used for all others.
here is simple thing u can do ,
float amount = 100000;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = formatter.format(amount);
System.out.println(moneyString);
The output will be Rs.100,000.00.
I also got myself in same problem.
I was working with DecimalFormat.
I have no knowledge of JSTL but you can figure out something by my solution.
As, grouping size remains constant in DecimalFormat. I separated both parts, formatted them with different patterns and concat both. Here is the code.
public static String format(double value) {
if(value < 1000) {
return format("###", value);
} else {
double hundreds = value % 1000;
int other = (int) (value / 1000);
return format(",##", other) + ',' + format("000", hundreds);
}
}
private static String format(String pattern, Object value) {
return new DecimalFormat(pattern).format(value);
}
It will provide format like Indian Numbering System.
If you want decimal points, just add ".##" in both conditions.
"###" to "###.##" and "000" to "000.##".
public String getIndianCurrencyFormat(String amount) {
StringBuilder stringBuilder = new StringBuilder();
char amountArray[] = amount.toCharArray();
int a = 0, b = 0;
for (int i = amountArray.length - 1; i >= 0; i--) {
if (a < 3) {
stringBuilder.append(amountArray[i]);
a++;
} else if (b < 2) {
if (b == 0) {
stringBuilder.append(",");
stringBuilder.append(amountArray[i]);
b++;
} else {
stringBuilder.append(amountArray[i]);
b = 0;
}
}
}
return stringBuilder.reverse().toString();
}
This is what i did, for getting Indian currency format. if input is 1234567890 means output is 1,23,45,67,890.
Try this:
NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(number)
"en" is for English.
"IN" is for the country (India).
Just Copy past this function. :)
public static String rupeeFormat(String value){
value=value.replace(",","");
char lastDigit=value.charAt(value.length()-1);
String result = "";
int len = value.length()-1;
int nDigits = 0;
for (int i = len - 1; i >= 0; i--)
{
result = value.charAt(i) + result;
nDigits++;
if (((nDigits % 2) == 0) && (i > 0))
{
result = "," + result;
}
}
return (result+lastDigit);
}
The simple solution is -
Double amount = 5356673553123.0; //amount is an example ,can be used with any double value
**DecimalFormat IndianCurrencyFormat = new DecimalFormat("##,##,###.00");**
then use it as -
String formattedAmount = IndianCurrencyFormat.format(amount);
Please find below snippet to print currency according to locale by giving inputs
import java.util.*;
import java.text.*;
public class CurrencyPayment {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
System.out.println("US: " + NumberFormat.getCurrencyInstance(Locale.US).format(payment));
System.out.println("India: " + NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(payment));
System.out.println("China: " + NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment));
System.out.println("France: " + NumberFormat.getCurrencyInstance(Locale.FRANCE).format(payment));
}
}
If there is no default Locale available and the user doesn't make any change to the locale, we can go with setting the currency symbol using unicode and decimal formatting. As in the below code:
For e.g. Setting the Indian currency symbol and formatting the value. This will work without user making changes in the settings.
Locale locale = new Locale("en","IN");
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
dfs.setCurrencySymbol("\u20B9");
decimalFormat.setDecimalFormatSymbols(dfs);
System.out.println(decimalFormat.format(payment));
Output:
₹12,324.13
On Android android.icu.text.NumberFormat is available after api level 24 only. So to support lower version I wrote my own method in java.
public static String formatIndianCommaSeparated(long rupee){
// remove sign if present
String raw = String.valueOf(Math.abs(rupee));
int numDigits = raw.length();
StringBuilder sb = new StringBuilder(raw);
// Reverse the string to start from right most digits
sb = sb.reverse();
// Counter to keep track of number of commas placed
int commas = 0;
for (int i=0; i<numDigits; i++){
// Insert a comma if i is in the range [3, 5, 7, 9, ...)
if (i % 2 == 1 && i != 1 ){
sb.insert(i+commas, ",");
commas++;
}
}
// Reverse the string back to get original number
String sign = (rupee < 0) ? "-" : "";
return sign + sb.reverse().toString();
}
Kotlin version, It works on Android API 26
fun currencyLocale(value: Double): String {
val formatter = NumberFormat.getCurrencyInstance(Locale("en", "in"))
return formatter.format(value)
}
fun parseCommaSeparatedCurrency(value: String): Number {
return NumberFormat.getCurrencyInstance(Locale("en", "in")).parse(value)
}
Few options that I explored are as below
import java.text.NumberFormat;
import java.util.Locale;
class NumberFormatDemo {
public static void main(String[] args) {
Double d = 45124853123456.78941;
NumberFormat nf = NumberFormat.getInstance(Locale.ITALY);
System.out.println("ITALY representation of " + d + " : " + nf.format(d));
nf = NumberFormat.getInstance(Locale.GERMANY);
System.out.println("GERMANY representation of " + d + " : " + nf.format(d));
nf = NumberFormat.getInstance(Locale.CHINESE);
System.out.println("CHINESE representation of " + d + " : " + nf.format(d));
nf = NumberFormat.getInstance(Locale.US);
System.out.println("US representation of " + d + " : " + nf.format(d));
nf = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println("ENGLISH representation of " + d + " : " + nf.format(d));
nf = NumberFormat.getInstance(Locale.UK);
System.out.println("UK representation of " + d + " : " + nf.format(d));
//===================================================
//ICU4j example
com.ibm.icu.text.NumberFormat format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println("INDIA representation of " + d + " : " + nf.format(d));
}
}
The last one reacquires following dependency
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>65.1</version>
</dependency>
//Input:
long num = 450500;
// Unlike other countries, there is no direct Locale field for India.Therefore, we need to construct a locale for India.
Locale loc = new Locale("en", "in"); // This will display currency with "Rs." symbol.
// or use below to display currency with "INR" symbol.
Locale loc = new Locale("", "in");
NumberFormat indiacurrency = NumberFormat.getCurrencyInstance(loc);
String result = indiacurrency.format(num);
System.out.print(result);
public static String paiseToString(long paise)
{
DecimalFormat fmt = new DecimalFormat("#0.00");
boolean minus = paise < 0;
StringBuilder sb = new StringBuilder(fmt.format(Math.abs(paise)/100.0));
for (int index = sb.length()-6; index > 0; index-=2)
{
sb.insert(index,',');
}
if (minus)
sb.insert(0,'-');
return sb.toString();
}
public static String rupeesToString(long rupees)
{
boolean minus = rupees < 0;
StringBuilder sb = new StringBuilder(Long.toString(Math.abs(rupees)));
for (int index = sb.length()-3; index > 0; index-=2)
{
sb.insert(index,',');
}
if (minus)
sb.insert(0,'-');
return sb.toString();
}
// Test the functions
public static void main(String[] args)
{
// Test for positive values
long val = 1;
while (val < Long.MAX_VALUE/10)
{
System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
val *= 10;
}
// Test for negative values
val = -1;
while (val > Long.MIN_VALUE/10)
{
System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
val *= 10;
}
}
The default methods in existing libraries can only show thousands seperator. so we need to write custom function for this. You can use multiple substring operation to get the desired result.
In java,
function indianCurrencyNumberFormat(rupee) {
string explore_remaining_units = "";
if (rupee.length() > 3) {
last_three_digits = rupee.substring((rupee.length()-3), rupee.length());
remaining_units = rupee.substring(0, (rupee.length()-3));
remaining_units = ((remaining_units.length()) % 2 == 1) ? "0"+remaining_units : remaining_units;
split_rupee = remaining_units.split("(?<=^(.{2})+)")
for (i = 0; i < sizeof(split_rupee); i++) {
explore_remaining_units += ((i == 0) ? ( (int) split_rupee[i]+"," ) : ( split_rupee[i]+"," ));
}
formatted_rupee = explore_remaining_units+last_three_digits;
} else {
formatted_rupee = rupee;
}
return formatted_rupee;
}
And in php:
function indianCurrencyNumberFormat($rupee) {
$explore_remaining_units = "";
if (strlen($rupee) > 3) {
$last_three_digits = substr($rupee, strlen($rupee) - 3, strlen($rupee));
$remaining_units = substr($rupee, 0, strlen($rupee) - 3);
$remaining_units = (strlen($remaining_units) % 2 == 1) ? "0".$remaining_units : $remaining_units;
$split_rupee = str_split($remaining_units, 2);
for ($i = 0; $i < sizeof($split_rupee); $i++) {
$explore_remaining_units .= (($i == 0) ? ( (int) $split_rupee[$i] . "," ) : ( $split_rupee[$i] . "," ));
}
$formatted_rupee = $explore_remaining_units.$last_three_digits;
} else {
$formatted_rupee = $rupee;
}
return $formatted_rupee;
}
You can see more details here.
import java.util.*;
public class string1 {
public static void main(String args[])
{
int i,j;
boolean op=false;
StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());
int length=sbuffer.length();
if(sbuffer.length()<3)
{
System.out.println("string="+sbuffer);
}
else
{
for ( i = sbuffer.length(); i >0; i--)
{
if (i==length-3)
{
sbuffer.insert(i, ",");
op=true;
}
while(i>1 && op==true)
{
i=i-2;
if(i>=1)
{
sbuffer.insert(i, ",");
}
}
}
}
System.out.println("string="+sbuffer);
}
}
It is better answer and works dynamically instead of specifying single Locale in code manually.
public String convertToDefaultCurrencyFormat(String amountToConvert){
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
String moneyString = formatter.format(Double.valueOf(amountToConvert));
return moneyString;
}
for Indian rupees format change Language in your Android device:
Setting > Language & Input Settings > choose English(India)
Output:
₹10,00,000 (Starting with Indian Rupee symbol)
Working fine for me in Android:
public static String priceFormatWithDec(String price) {
DecimalFormat decimalFormat = new DecimalFormat("#,##,###.00");
String format = decimalFormat.format(Double.parseDouble(price));
return String.format("%s", format);
}
using Locale class and getCurrencyInstance the Indian currency format can be obtained.
while defining the new Locale for India use "en" for English and "hi" for Hindi.
for locale refer https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html
for getCurrencyInstance refer https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getCurrencyInstance--
here is a small implementation of the same.
import java.util.*;
import java.text.*;
import java.text.NumberFormat;
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
Locale indialocale=new Locale("en","IN");
NumberFormat india = NumberFormat.getCurrencyInstance(indialocale);
System.out.println("India: " + india.format(payment));
}
}
This is working for me ..
public String indianCurrencyFormat(String s) {
String orignalNo = s;
String formatted = "";
if(orignalNo.startsWith("-")) {
s = s.replace("-","");
}
if(orignalNo.contains(".")) {
if(s.length() > 6){
StringBuilder sb=new StringBuilder(s);
s = sb.reverse().toString();
formatted = s.substring(0,6);
s = s.substring(6);
while(s.length() > 1) {
formatted += "," + s.substring(0,2);
s = s.substring(2);
}
sb = new StringBuilder(formatted+(StringUtils.isNotBlank(s) ? ","+s :""));
formatted = sb.reverse().toString();
} else {
formatted = s;
}
} else {
if(s.length() > 3){
StringBuilder sb=new StringBuilder(s);
s = sb.reverse().toString();
formatted = s.substring(0,3);
s = s.substring(3);
while(s.length() > 1) {
formatted += "," + s.substring(0,2);
s = s.substring(2);
}
sb = new StringBuilder(formatted+(StringUtils.isNotBlank(s) ? ","+s :""));
formatted = sb.reverse().toString();
} else {
formatted = s;
}
}
if (orignalNo.startsWith("-")){
formatted = "-"+formatted;
}
return formatted;
}
It worked for me:
fun getFormattedPrice(price: Double?): String {
if (price == null) return "0"
val formatter = DecimalFormat("##,##,###.00").format(price)
var formattedPrice = formatter.format(price)
if (formattedPrice.endsWith(".00")) formattedPrice = formattedPrice.dropLast(3)
if (formattedPrice.isEmpty()) formattedPrice = "0"
return formattedPrice
}
Try this:
double number = 100000.00
NumberFormat numberFormat = new NumberFormat();
Locale locale = new Locale("hi","IN");
numberFormat = Numberformat.getCurrencyInstance(locale);
double yourFormattedNumber = numberFormat(number);
OutPut = ₹1,00,000.00
//Remove "₹" using String.replace()
String myFormattedNumber = numberFormat.format(number).replace("₹","");
OutPut = 1,00,000.00
fun currencyFormatter(inputNumbers: String?): String {
var formattedNumber = ""
var decimalPoint=""
var inputNumber=""
if (inputNumbers != null) {
try {
val sp=inputNumbers.split(".")
inputNumber=sp[0]
decimalPoint=sp[1]
} catch (e: Exception) {
inputNumber=inputNumbers
}
formattedNumber = when {
inputNumber.length <= 3 -> {
inputNumber
}
inputNumber.length <= 5 -> {
String.format("%s,%s", inputNumber.substring(0, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3))
}
inputNumber.length <= 7 -> {
String.format("%s,%s,%s",
inputNumber.substring(0, inputNumber.length - 5),
inputNumber.substring(inputNumber.length - 5, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3)
)
}
inputNumber.length <= 9 -> {
String.format("%s,%s,%s,%s",
inputNumber.substring(0, inputNumber.length - 7),
inputNumber.substring(inputNumber.length - 7, inputNumber.length - 5),
inputNumber.substring(inputNumber.length - 5, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3)
)
}
else -> inputNumber
}
}
return "$formattedNumber.$decimalPoint"
}
main(){
val rs=1200.55f
print(currencyFormatter(rs.toString()))
}
Converting any Number into Indian Rupee Format in Golang.
Function IndianRupeeFormat takes paramter as string and returns as string
func IndianRupeeFormat(DisplayAmount string) string {
AmountDisplayed := DisplayAmount[:len(DisplayAmount)-3] // just removing decimal point numbers.
IndianRupee := ""
if len(AmountDisplayed) > 3 { // amount should to greater than 999 if "," should appear , so length should be greater than 3
startIndex := math.Mod(float64(len(AmountDisplayed)), 2) // startIndex is taken as slicing part to add comma.
noOfCommas := (len(AmountDisplayed) / 2) - 1 // No of Commas appear in the number.
startSlice := 0 // start of the slice
for i := 0; i < noOfCommas; i++ {
IndianRupee = IndianRupee + DisplayAmount[startSlice:int64(startIndex)+1] + ","
startIndex = startIndex + 2 // adding +2 because after first comma we are skipping 2 digits to add another comma.
startSlice = int(startIndex) - 1
}
k := len(DisplayAmount) - 6
IndianRupee = IndianRupee + DisplayAmount[k:] // adding the rest of digits.
} else {
IndianRupee = DisplayAmount
}
return IndianRupee
}
Amount1 := IndianRupeeFormat(fmt.Sprintf("%.2f",100))
Amount2 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000.345))
Amount3 := IndianRupeeFormat(fmt.Sprintf("%.2f",10000.02))
Amount4 := IndianRupeeFormat(fmt.Sprintf("%.2f",100000.100))
Amount5 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000000.))
Amount6 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000.090))
fmt.Println(Amount1)
fmt.Println(Amount2)
fmt.Println(Amount3)
fmt.Println(Amount4)
fmt.Println(Amount5)
fmt.Println(Amount6)
// Output: 100
// Output: 1,000.34
// Output: 10,000.02
// Output: 1,00,000.10
// Output: 10,00,000.00
// Output: 1,000.90
I know this is an old question but I'll add my answer just in case. It is possible to use the same decimal formatter in a roundabout way to achieve the result but it isn't the most efficient solution, just a simpler one.
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class IndianMoneyFormat {
static String indianCurrencyFormat(double money) {
String result = null;
double aboveThousands = money / 1000;
double thousands = money % 1000;
if (aboveThousands > 1) {
DecimalFormat formatter = new DecimalFormat("##,##");
formatter.setRoundingMode(RoundingMode.DOWN); //will round towards zero whether negative or positive. Same as truncating.
String one = formatter.format(aboveThousands);
formatter.applyPattern("###.00");
formatter.setRoundingMode(RoundingMode.HALF_EVEN); //default rounding mode of DecimalFormat
String two = formatter.format(thousands);
result = one + "," + two;
return result;
} else {
DecimalFormat formatter = new DecimalFormat("###.00");
result = formatter.format(money);
return result;
}
}
public static void main(String[] args) {
double money1 = 123000999.5;
double money2 = 999.39;
System.out.println(indianCurrencyFormat(money1));
System.out.println(indianCurrencyFormat(money2));
}
}
Above code will provide the following result:
12,30,00,999.50
999.39
ALTER FUNCTION [dbo].[udf_CurrencyFormat](#UC varchar(50)) RETURNS
varchar(50) AS BEGIN declare #FC varchar(50),#Scale varchar(3),#i
bigint=1,#a int=3,#b int=2,#WhileLength bigint,#UCScale varchar(50),
#Con varchar(20) set #Scale=charindex('.',#UC) --if number has '.'
then value else '0' if(#Scale!='0') begin set #UCScale=#UC set
#Con=substring(#UCScale,charindex('.',#UCScale),3) set
#UC=substring(#UC,0,charindex('.',#UC)) -- substring end
if(cast(len(#UC) as bigint)%2!=0) --if odd begin set
#WhileLength=(cast(len(#UC) as bigint)-3)/2 while(#i<=#WhileLength) --
length-3/2=3 if length is 9 (cast(len(#UC) as bigint)-3)/2 begin set
#a=3*#i set #UC = stuff(#UC,#a,0,',') set #i=#i+1 end --while set
#FC=#UC end --if odd Scale '0' else if(cast(len(#UC) as bigint)%2=0)
--if even begin set #WhileLength=(((cast(len(#UC) as bigint)-1)-3)/2)+1 while(#i<=#WhileLength) begin if(#i=1) begin set
#UC=stuff(#UC,#b,0,',') end else begin set #b=#b+3 set
#UC=stuff(#UC,#b,0,',') end set #i=#i+1 end set #FC=#UC end
if(#Scale!='0') begin set #FC=#FC+#Con end --if(#Scale!='0') --set
#FC=#UC return #FC END

Java: How to format String number with tenth exponent

I have a number as a string like this: "9.756088256835938E-4" but I only can use a specified number of characters (in this special case 9 char). So I want to have something like this: "9.7561E-4". I already tried to convert the String to a Double and then used the format method to get a less characters but I don't got a correct solution.
The problem is that I need ten exponential output since some numbers are longer than the number of characters I have. If it is possible, the number should be displayed with no ten exponent, if not just use the ten exponent.
Also correct rounding would be good.
And it should work for negative numbers. (minus needs one character!!!)
Is there a format function where I can define the maximum length of the output string? Any ideas?
I'm having trouble findind a single format pattern that will cover all of the cases that you described. But here's a combination of logic that I think works:
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
String out = null;
for ( int i = 0; i < MAX_LENGTH; i++ ) {
String format = "%." + i + "G";
out = String.format(format, number);
if ( out.length() == MAX_LENGTH ) {
return out;
}
}
return out; //the best we can do
}
The "G" in the pattern instructs the formatter to forego the use of the exponent when it will allow for the same or better precision. We grow up to the maximum length and stop when our output string is 10 characters. I think you could take the same approach with a DecimalFormat, but I'm more familiar with Formatter.
Seeing the Mark's example meet your requirements, I updated my answer to show the DecimalFormat implementation. I used Mark's test cases. It is definitely an uglier option because there is no easy way to turn on/off exponents. The only advantage over the String.format option is that it handles very small numbers well.
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
int digitsAvailable = MAX_LENGTH - 2;
if (Math.abs(number) < Math.pow(10, digitsAvailable)
&& Math.abs(number) > Math.pow(10, -digitsAvailable)) {
String format = "0.";
double temp = number;
for (int i = 0; i < digitsAvailable; i++) {
if ((temp /= 10) < 1) {
format += "#";
}
}
return new DecimalFormat(format).format(number);
}
String format = "0.";
for (int i = 0; i < digitsAvailable; i++) {
format += "#";
}
String r = new DecimalFormat(format + "E0").format(number);
int lastLength = r.length() + 1;
while (r.length() > MAX_LENGTH && lastLength > r.length()) {
lastLength = r.length();
r = r.replaceAll("\\.?[0-9]E", "E");
}
return r;
}
This reminded me of a similar question where the OP only had 5 or so spaces for a number and wanted to show a decimal only when there was enough space. But instead of exponents, wanted to use a suffix of (k,m, etc)

Categories

Resources