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

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.

Related

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 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?

Regex to find a price within a string

Hi a service I am using returns prices in the form 00003600 or 00013650
I would like to transform this to a string of the form 36.00 Euro or 136.50 Euro.
Can this be done using regex.
Thanks,
just parse the string and then divide by 100. Or use BigDecimal and scale.
In case the other answers were not clear enough
String text = "00003600";
BigDecimal value = new BigDecimal(text).scaleByPowerOfTen(-2);
System.out.println(value);
prints
36.00
OR
String text = "00003600";
double value = Double.parseDouble(text) / 100;
System.out.printf("%.2f%n", value);
prints
36.00
Most correct way (IMHO):
String input = "00013650";
BigDecimal value = BigDecimal.valueOf(Long.parseLong(input), 2);
String output = value.toPlainString();
System.out.println(output);
Outputs:
136.5

How to format numbers with no grouping separator

I'm trying to format a BigDecimal value by using methods of DecimalFormat.format().
My problem, is I don't know how to set DecimalFormats DecimalFormatSymbol to format text without any grouping separators.
I'd like to know how to set a grouping symbol and use the format methods. I know how to do it differently by using replace or others methods but it's not what I want.
So I need to know how to set an empty character as grouping operator.
Example:
DecimalFormat dec = new DecimalFormat();
DecimalFormatSymbols decFS = new DecimalFormatSymbols();
decFS.setGroupingSeparator( '\0' );
dec.setDecimalFormatSymbols( decFS );
BigDecimal number = new BigDecimal(1000);
String result = dec.format(number);
I want to get "1000" as string with no other characters. Please help
note(react to post): I want to formate the number only, without grouping.
Simply:
DecimalFormat dec = new DecimalFormat();
dec.setGroupingUsed(false);
If you dont want any formatting marks in the number you should just call toString on the BigDecimal Object.
import java.math.*;
public class TestBigDecimal
{
public static void main(String[] args)
{
BigDecimal number = new BigDecimal(1000);
String result = number.toString();
}
}
String result = String.valueOf(number);
returns your number as a string with no formatting.

How to convert string numbers into comma separated integers in 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));

Categories

Resources