How to convert string numbers into comma separated integers in java? - java

Can any one give me some predefined methods or user defined methods to convert string numbers(example: 123455) to comma separated integer value (example: 1,23,455).

int someNumber = 123456;
NumberFormat nf = NumberFormat.getInstance();
nf.format(someNumber);

use java.text.NumberFormat, this will solve your problem.

Finally I found an exact solution for my needs.
import java.math.*;
import java.text.*;
import java.util.*;
public class Mortgage2 {
public static void main(String[] args) {
BigDecimal payment = new BigDecimal("1115.37");
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = payment.doubleValue();
String s = n.format(doublePayment);
System.out.println(s);
}
}

I assume 123455 is a String.
String s = 123455;
String s1 = s.substring( 0 , 1 ); // s1 = 1
String s2 = s.substring( 1 , 3 ); // s2 = 23
String s3 = s.substring( 2 , 7 ); // s3 = 455
s1 = s1 + ',';
s2 = s2 + ',';
s = s1 + s2; // s is a String equivalent to 1,23,455
Now we use static int parseInt(String str) method to convert String into integer.This method returns the integer equivalent of the number contained in the String specified by str using radix 10.
Here you cannot convert s ---> int . Since int does not have commas.If you try to convert you will get the following exception java.lang.NumberFormatException
you should use DecimalFormat Class. http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

What you're looking for is the DecimalFormat class (here), where you can set easily separator and convert a String to a Number with the method parse() for example.

The result you expected that is "to comma separated integer value", is in my opinion incorrect. However, if you are just looking for output representation, how about these lines of codes shown below? (Note, you can not parse the value return from valueToString to some data type long because it just does not make sense :) )
MaskFormatter format = new MaskFormatter("#,##,###");
format.setValueContainsLiteralCharacters(false);
System.out.println(format.valueToString(123455));

Related

how to cut all string "0" before other string number [duplicate]

This question already has answers here:
Trim leading or trailing characters from a string?
(6 answers)
Closed 2 years ago.
I have data like this for price number from my broker:
String Price = "00000001970.00";
String Price1 = "0000000295.00";
This is the code I tried to use:
String Price2 = price.replace ("0", "");
But result was Price2 = 197. and my expectation is Price2=1970.
Can someone tell me how to fix this problem?
String price = "00000001970.00";
// If you don't care about the decimals
System.out.println(price.split("\\.")[0].replaceFirst("^0+(?!$)", ""));
// If you do care about the decimals:
System.out.println(price.replaceFirst("^0+(?!$)", ""));
See How to remove leading zeros from alphanumeric text?
You need to use a Regex like this:
yourstring.replaceFirst("^0+(?!$)", "");
guy. There was a sea of solutions to resolve your problem. For instance, you can look up like below:
` String price = "00000001970.00";
Double dv = Double.valueOf(price);
System.out.println(dv);
int intValue = dv.intValue();
System.out.println(intValue);
`
And you will get a result like below:
`
1970.0
1970`;
Besides, you can also look up like below:
` String price = "00000001970.00";
String substring = price.substring(0,price.indexOf("."));
System.out.println(Integer.valueOf(substring));
`
I'm personally not a big fan of regexes so I avoid them whenever possible.
Assuming that all your Strings are numeric, you could parse them to BigDecimal and then print that however you want. BigDecimal is prefer over Double if you care about precision.
To achieve what you want you could do something like so:
public static void main(String args[]) {
String price = "00000001970.00";
String price1 = "0000000295.0011";
BigDecimal num = new BigDecimal(price);
BigDecimal num1 = new BigDecimal(price1);
DecimalFormat df = new DecimalFormat("#.###");
System.out.println(df.format(num));
System.out.println(df.format(num1));
}
Those numbers will be formatted as so:
1970
295.001
To learn more about possible formats read DecimalFormat Javadocs.
Double#parseDouble
public class Main {
public static void main(String[] args) {
String strPrice = "00000001970.00";
double price = Double.parseDouble(strPrice);
System.out.println(price);
}
}
Output:
1970.0
The simplest way seems to use method replaceFirst from class org.apache.commons.lang3.RegExUtils (Apache Commons):
String price = RegExUtils.replaceFirst("00000001970.00", "0+(\\d)", "$1");
This will replace a substring of first zeros followed by any digit by this digit.

How to perform mathematical operation on numbers in java having comma instead of decimal? [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 4 years ago.
Say i have 2 strings "123,21" and "22,41" i want to subtract both these numbers and return the output in String format itself in Java.
I am unable to identify how can i use Number.format() to do this.
Also how can i convert this string to big decimal?
First, you can follow this way to use Number.format().
Then, you can simply create BigDecimal with the double result.
After various exchange via comments, this is my final answer, allowing to control decimal separator, and grouping separator:
public static final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2, char separator, char groupingSeparator)
throws ParseException {
Locale myLocale = Locale.FRANCE;
DecimalFormatSymbols decimalSeparator = new DecimalFormatSymbols(myLocale);
decimalSeparator.setDecimalSeparator(separator);
decimalSeparator.setGroupingSeparator(groupingSeparator);
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(myLocale);
format.setDecimalFormatSymbols(decimalSeparator);
Number number1 = format.parse(stringNumber1.trim());
Number number2 = format.parse(stringNumber2.trim());
double substractResult = number1.doubleValue() - number2.doubleValue();
// If you want back a String presentation => String stringFormat = "" +
// substractResult;
return new BigDecimal(substractResult);
}
This way you fully control locale and decimal separator as you wish.
If you want to use coma as default decimal separator, you can add this overload:
public final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2)
throws ParseException {
return convertToBigDecimal(stringNumber1, stringNumber2, ',', '.');
}
public final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2, char separator)
throws ParseException {
return convertToBigDecimal(stringNumber1, stringNumber2, separator, '.');
}
You can then easily use this new function
System.out.println(convertToBigDecimal("123,21", "22,41", ','));
System.out.println(convertToBigDecimal("123.21", "22.41", '.'));
System.out.println(convertToBigDecimal("123,441.33", "122,441.22", '.', ','));
System.out.println(convertToBigDecimal("59.998,50", "698,43", ',', '.'));
System.out.println(convertToBigDecimal("59.998,50", "49.998,50", ','));
I think decimal format with this custom formatting can be provided to convert the text to an integer or double as per requirement.
public static void main(String[] args) throws ParseException {
String text1 = "123,21";
String text2 = "22,41";
NumberFormat nf_in = new DecimalFormat("###,##");
int number1 = nf_in.parse(text1).intValue();
System.out.println("Number 1 "+number1);
int number2 = nf_in.parse(text2).intValue();
System.out.println("Number2 "+number2);
System.out.println("Subtract Number2 from number 1"+ (number1-number2));
}
public static void main(String[] args) throws ParseException {
String text1 = "123,21";
String text2 = "22,41";
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator(',');
NumberFormat nf_in = new DecimalFormat("##,##",decimalFormatSymbols);
double number1 = nf_in.parse(text1).doubleValue();
System.out.println("Number 1 "+number1*1);
double number2 = nf_in.parse(text2).doubleValue();
System.out.println("Number2 "+number2*1);
double outputvalue = number1 - number2;
System.out.println( outputvalue);
}
I think using DecimalFormatSymbols with Decimal format should do allow you to use comma as the decimal symbol.
Refer Best way to parseDouble with comma as decimal separator?
You maybe want to values next to comma and subtract them. A common and a handy way I know is using split() method that will return an array of strings.
String text = "123,21";
String[] values = text.split(","); //this will add all the strings before or after a ",".
String answer = (Integer.parseInt(values[0])-Integer.parseInt(values[1])).toString();
System.out.println("Answer: "+answer); //will output 102

How to split string by ± in java

I was trying to split my string using ± (alt + 0177) sign, but it dos't detect it.
I also tried indexOf() but its not work
String myString = "20±1";
if(myString.indexOf('±')>-1){
System.out.println("We are in here.........");
}
You can use the ascii value for the '±' sign.
An easy way get the ascii value as shown in this reply here
In your case:
final int ascii = (int) '±';
final String myString = "20±1";
if(myString.indexOf(ascii)>-1){
System.out.println("We are in here.........");
}
Use function split()
String myString = "20±1";
String result[] = myString.split("±");
//result[0] = 20
//result[1] = 1
/*Your String*/
String myString = "20±1";
/*If you want to split String you can use String.split("your string regex here")
* and it will create String array without specified string regex with left, right
* side of string or multiple strings depending on occurrence of specified string regex*/
String[] splitted = myString.split("±");
/*Just to validate output*/
System.out.println(Arrays.toString(splitted));
you can use also StringTokenizer for this problem:
import java.io.*;
import java.util.*;
class happy {
public static void main(String args[])
{
String myString = "20±1";
StringTokenizer st=new StringTokenizer(myString,"±");
String a="";
while(st.hasMoreTokens())
{
a=st.nextToken();
System.out.println(a);
}
}
}

How to parse BigDecimal into Text with EU decimal separator but no decimal numbers at the end?

I need to be able to be able to parse a "1.000," string into a BigDecimal with value 1000
and then parse that same BigDecimal back into a "1.000," string.
Both should happen using the same exact DecimalFormat formatter.
Why? Because I need to compare at the end of each stage whether the two strings are equal, meaning whether the parsing was correct or not.
So far I tried to use these two patterns: DecimalFormat("###.##0,") and DecimalFormat("0,") but they don't produce the exact "1.000," at the end.
Here's my code:
List<NumberFormat> formats = new ArrayList<NumberFormat>();
formats.add(DecimalFormat("###.##0,"));
formats.add(DecimalFormat("0,"));
for(NumberFormat format : formats) {
Number number = format.parse(text);
format.setParseIntegerOnly(false);
if (number != null && format(format, number).equals(text)) {
return true;
}
}
I actually figured this out.
I had to define the patterns as
DecimalFormat("###,##0.", new DecimalFormatSymbols(Locale.GERMAN))
and
DecimalFormat("0.", new DecimalFormatSymbols(Locale.GERMAN))
and I had to add this to the NumberFormat object:
format.setParseIntegerOnly(false);
to make it work for EU numbers.
Maybe you should consider using Regex for your problem.
You can replace , for . and add 000 at the end.
String str = "10,1";
str = str.replaceAll(",", ".");
System.out.println(str);
This will print "10.1"
EDIT:
String str = "1.000,";
str = str.replaceAll(",", "");
str = str.replaceAll(".", "");
int bigDecimal = Integer.valueOf(str);
//first part is done
System.out.println(str);
String regex = "(\\d)(?=(\\d{3})+$)";
String result = bigDecimal.toString();
result = result.replaceAll(regex,".");
result = result + ",";
Is this what you are looking for?

How to convert an integer according to international number system in java (Number Formatting)

I want to convert a given number according to international number system. // For example:
345678 -> 345,678
12 -> 12
123 -> 123
4590 -> 4,590
Here is the code snippet and IdeOne link
public static void main (String[] args) throws java.lang.Exception
{
int number = 345678;
String s = Integer.toString(number);
s = putCommas(s);
}
private String putCommas(String s) {
// How to put commas in string after every 3rd character from right ?
}
Here is my approach with which I am not comfortable.
Start traversing string from right
If the (length - currentIndex -1) % 3 == 0 insert comma in the string
Any suggestions ?
You can use NumberFormat with Locale#US:
NumberFormat.getNumberInstance(Locale.US).format(number);
Or DecimalFormat:
DecimalFormat formatter = new DecimalFormat("#,###");
String newNumber = formatter.format(number);
Use the NumberFormat class
http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#getInstance(java.util.Locale)
You can pass it in a Locale and then format the number as required
http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#format(long)
System.out.println (NumberFormat.getNumberInstance(Locale.US).format(1234567L));
You can use simply NumberFormat class .
NumberFormat numberFormat = NumberFormat.getInstance();
//allows to have number seperated by comma
numberFormat.setGroupingUsed(true);
String formattedNr = numberFormat.format(12345678L);
System.out.println("12345678L number formatted to " + formattedNr);
Output:
12345678L number formatted to 12,345,678.00

Categories

Resources