Trimming text in java - java

is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));
note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)
is any method in java to trimming decimal number to simplify my works? (not trim() function)
Edit: the number of decimal place is specified by user input.

The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.
It would be something like this:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
String pattern = "#.00";//this means that you want only 2 decimals
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.parse("221012,28").doubleValue());
System.out.println(decimalFormat.format(1234.123121));
That prints
221012.28
1234,12

You could try using String.format. First switch the comma with a period. For example,
number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");
First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.
Hope this helps!

As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.

Related

How to print entire number even after removing decimal point?

I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);

How to store a value greater than "999" in double while using parseDouble function?

I am not able to store value greater than "999" while using parseDouble function. This is my code:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmt.getText().toString())));
It is only storing value upto "999" not greater than that. It does not allow me to store value "1000" or greater.
Error message:
java.lang.NumberFormatException: For input string: "123,456.78"
The default method NumberFormat.format(String) automatically puts a comma separating thousands when setting it to formatted text. This comma can not be parsed into a double datatype because it only accepts '.' as the decimal split character and numbers around it.
This can be seen by this test:
double amount = Double.parseDouble(formatter.format(Double.parseDouble("1000")).replace(",", ""));
If the number requires a comma then use the .replace() method to replace it when parsing it to a double. Otherwise use a custom instantiation for your Number formatter such as:
NumberFormat formatter = new DecimalFormat("0000.00");
I am working under the assumption that balanceAmt.getText().toString() is returning 123,456.78 or similar.
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmy.getText().toString().replace(",", ""))).replace(",", ""));
System.out.print(amount);
When you get the balance from balanceAmt, it has the comma, so you have to remove it. When if goes through the formatter, it re-adds the comma back, meaning you have to remove it again before the second parseDouble is done.

Java - Format a String to show a pound sign and a decimal with two leading zeroes using objects and the toString method?

I have tried
System.out.println(myLorry.toString(registration, myCar.calcCharge()));
which outputs
Registration: TA17 NDD Charge: 7.0
I want my program to output
Registration: TA17 NDD Charge: £7.00
How can I format this correctly?
EDIT:
Why doesn't formatting work correctly? It says it's expecting two parameters but can only find one. I need to call objects using the toString method.
System.out.printf("%s £%.2f" ,myCar.toString(registration, myCar.calcCharge()));
like #davidxxx suggest in comment you can use
DecimalFormat d = new DecimalFormat("'£'0.00");
System.out.println(d.format(7.0));
Output
£7,00
If you have a problem with dot(.) and comma(,) then you can use DecimalFormatSymbols :
DecimalFormat d = new DecimalFormat("'£'0.00");
DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
sym.setDecimalSeparator('.');
d.setDecimalFormatSymbols(sym);
one solution is to use the printf.
e.g.
double value = 7.0;
System.out.printf("%s%.2f","£", value);
output:
£7.00
In fact you should consider two things :
formatting the number value with the fixed number of digits for the floating part.
setting the decimal separator character.
The second point may matter as according to the locale set by the JVM, you could get a distinct result : £7.00 or £7,00
So, you could specify the "£0.00" pattern in DecimalFormat and create the DecimalFormat instance with a specific DecimalFormatSymbols that ensures that you will use as decimal symbol the . character.
You could do it for example :
float f = 7;
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator('.');
NumberFormat formatter = new DecimalFormat("£0.00", otherSymbols);
String valueFormated = formatter.format(f);
But in fact a more simple way would be to use the String.format() method by specifying both the expected pattern (two digits for the floating part) and a Locale that uses the . as decimal separator :
float f = 7;
String valueFormated = String.format(Locale.US, "£%.2f", f);
Solved it! I was looking in completely the wrong part of my program, here is my solution:
String toString(String rn, double calcCharge)
{
DecimalFormat d = new DecimalFormat("£0.00");
return "Registration: " + rn + " Charge: " + d.format(calcCharge());
}
I had to modify a class that my subclasses inherited from.

Convert String to Number with Format

I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");

Convert to int from String of numbers having comma

I have value like this:
String x = "10,000";
I want to convert this to int.
I can convert it by removing comma like below:
String y = x.replace(",", "");
int value1 = Integer.parseInt(y);
But I don't want to do it like above.
Any other suggestions like inbuilt function? Or any other recommended ways for this?
You can simply:
NumberFormat.getNumberInstance(Locale.UK).parse(x);
Read about:
NumberFormat
Locale.UK and others.
Try this:
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("10,000");
// Now you can get number values from the object (like int, long, double)
System.out.println(number.intValue());
Output:
10000
Note: If you string contains values after decimal point, you need to use number.doubleValue to retain the precision because number.intValue() will simply ignore values after decimal points.
Use any one of these:
NumberFormat.getNumberInstance(Locale.ENGLISH).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.US).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.UK).parse("10,000").intValue();

Categories

Resources