Java Object format to String Number with Decimals - java

so I have an array list of Objects and in it are string numbers. I want to add decimal places to these numbers (8).
String value = String.valueOf(accountEntry.get(4));
double amount = Double.valueOf(value);
String formatted = String.format(Locale.GERMANY,"%.8f",amount);
accountEntry.add(formatted);
For example 101700000000 should output 1017 but instead it is 101700000000,00000000
Does anyone know where the problem is?

Hello try something like this using Regex , this way you can remove all zeros at the end.
String value = String.valueOf("101700000000");
double amount = Double.valueOf(value);
String formatted = String.format(Locale.GERMANY,"%d",(long)amount);
formatted = formatted.replaceAll("0+$", "");
System.out.println(formatted);
Input :101700000000 ===> Output: 1017

Does anyone know where the problem is?
Your Input is : 101700000000 and you are formatting String.format(Locale.GERMANY,"%.8f",amount); In here your output will be 101700000000,00000000 So for understand this String Format will not transform your input magicaly to 1017. You need to use another algorithm for this problem

Related

How to convert a string with multiple points to double in android

I have a string "3,350,800" with multiple points I want to convert to double but have error multiple points
String number = "3,350,800"
number = number.replace(",", ".");
double value = Double.parseDouble(number);
Error : java.lang.NumberFormatException: multiple points
The . character is used as a decimal point in English, and you cannot have more than one of those in a number.
It seems like you're using it as a thousands separator though. This is legal in several locales - you just need to use one that allows it, e.g.:
String number = "3.350.800";
NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
double value = format.parse(number).doubleValue();
Mix of other answers, no reason to change the , for . and then fetch the German local.
String number = "3,350,800";
NumberFormat format = NumberFormat.getInstance();
double value = format.parse(number).doubleValue();
System.out.println(value);
Output:
3350800.0
you need to use something like this :
String number = "3,350,800";
number = number.replaceAll(",", "");
double value = Double.parseDouble(number);
System.out.println(value);
What number are you trying to get?
3.350.800 is what you're trying to parse as a double,
but that's obviously not a number, since there are "multiple points".
If you just wanna get 3,350,800 as your number, simply change this line -
number = number.replace(",", ".");
to this -
number = number.replace(",", "");

How can i get both float and string in output?

How can I obtain the output 6214.07500000sec
I am reading this data from the file and trying to insert in a table. I am getting an error because of string error .
I have tried to parse:
float t_f = Float.parseFloat(td)
Doesn't help.
Please give a suggestion for getting both string and floating number.
def output = '6214.07500000sec'
Map data = (output=~/(\d+(\.\d+)?)(.*)/).find{true}.with{ m->
return [ value: m[1] as Float, measure: m[3] ]
}
println data
result:
[value:6214.075, measure:sec]
You can't store the full String in a float since you got the "sec" at the end, one solution could be as #notyou said in the comments to store everything in a string, another solution could be to separate the letters from the numbers, here's a short code that will do the trick:
String output = "6214.07500000sec";
String letters;
float number;
Scanner scan = new Scanner(output);
number = Float.parseFloat(scan.findInLine("\\d+(\\.\\d+)?"));
letters = scan.next();
System.out.println(number);
System.out.println(letters);
this code prints:
6214.075
sec
if you want all the zeros you have to store it as a String.

Decimal places to 2 values in Selenium Webdriver using Java

Could someone help with the following scenario.
In a textfield, i will give input say
String input1 = "120.3456";
But system will automatically take 2 decimal points and displays "120.35"
Now i will store using getAttribute("value") into a different string say
String getValue = driver.findElement(By.xpath("html/....xpath of the text field")).getAttribute("value");
How can i validate that my given input value is rounded to 2 decimal points in Selenium Webdriver?
Would be grateful if someone can provide me the best approach. Thanks in advance
Try as below :-
String input1="120.3456";
String getValue = driver.findElement(By.xpath("html/....xpath of the text field")).getAttribute("value");
String str = new BigDecimal(input1).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
return str.equals(getValue)
Hope it helps...:)
You can do it simply as below. You'll need to take the input and value strings and convert them to double. You'll need to round input and compare to value. This returns true if the two values are equal, false otherwise.
String input1 = "120.3456";
double input1Rounded = Math.round(Double.parseDouble(input1) * 100.0) / 100.0;
String value = driver.findElement(locator).getAttribute("value");
double valueRounded = Double.parseDouble(value);
return (input1Rounded == valueRounded);

Right Align String NumberFormat in Java

I need to right align an input string of digits with a mask using plus symbols.
For example:
String input = "893";
String mask = "&&&&&&";
should return
String output = "+++893";
I'm very confused on how to implement this with NumberFormat and or DecimalFormat as I haven't used them before. Any help would be appreciated.
If you need to use DeciamlFormat you could use:
int input = 893;
DecimalFormat decFormat = new DecimalFormat("000000"); //as many palces as you need
String output = decFormat.format(input);
And then replace all leading zeros with + sign.
String.format("%06d", input); //also gives you leading zeros
You still have to check if the output is too long, if you always want 6 places.
You could try this: If the length of the mask is greater than the length of the input, take the difference and add that many plus signs to the front of the input.

How can I format a String number to have commas and round?

What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.
For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.
String.format("%,d", 2000000)
outputs:
2,000,000
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)
It supports:
Comma Formatting E.g. 1234567 becomes 1,234,567.
Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
Precision of 0 through 15.
Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).
The code can be found here. You call it like this:
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.
you can also use the below solution
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
Here is the simplest way to get there:
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
output:
10,987,655.88
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me.
Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
According to chartGPT
Using DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);
Using NumberFormat:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);
Using String.format():
String formattedNumber = String.format("%,.2f", yourNumber);
Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.

Categories