I have the following number:
1.0645208E10, which is in my case a double value. I would like to convert it into 106.45.
Any recommendation how to get 106.45?
I appreciate your answers!
You can try this:
double bigDouble = 1.0645208E10;
String strDouble = String.format(Locale.ENGLISH, "%.2f", bigDouble/100000000);
System.out.println(strDouble);
It will give you 106.45
But be aware of the fact that the output has nothing to do with the original value!! Is one hundred million times smaller...
Any recommendation how to get 106.45?
If you want to get only output then you can do following.
Double d = 1.0645208E10;
String s = d.toString().replace(".", "");//Converts into string and removes dot (.)
String s1 = s.substring(0, 5);//it gets only first 5 characters
String s2 = s1.substring(0, 3) + "." + s1.substring(3, 5);//it adds decimal point after first 3 character
System.out.println("Expected Output: " + s2);
Related
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(",", "");
The following code:
String a = "100.00";
String b = "10.00";
String c= "5.00";
String value = a+ "\n"+ b +"\n" +c;
System.out.println(value);
Prints:
100.00
10.00
5.00
I need output in a format where decimal point position will be fixed without using any string format library (with logic):
100.00
10.00
5.00
Variable values are coming from the database and requirement is to show values with the decimal point in the same position with values vertically.
Here's an example using streams; probably could be more efficient but I was having fun.
It assumes all have 2 decimals as you showed, just FYI; that could be modified though.
String a = "100.00";
String b = "10.00";
String c= "5.00";
List<String> strings = Arrays.asList(a, b, c);
final int maxLen = strings.stream().map(String::length).reduce(Math::max).get();
strings.forEach(s -> {
System.out.println(Stream.generate(() -> " ").limit(maxLen - s.length()).collect(Collectors.joining()) + s);
});
Results:
100.00
10.00
5.00
I also put pthe 3 examples into a list so it would work on an arbitrary number of elements.
Without Java 8
String a = "100.00";
String b = "10.00";
String c = "5.00";
List<String> strings = Arrays.asList(a, b, c);
int maxLen = -1;
for (String s : strings) maxLen = Math.max(maxLen, s.length());
for (String s : strings) {
String spaces = "";
for (int i = 0; i < maxLen - s.length(); ++i) {
spaces += " ";
}
System.out.println(spaces += s);
}
I don't know what 'don't use any String format library' means specifically, but... now we get into a semantic argument as to what 'library' means. You're formatting a string. If I take your question on face value you're asking for literally the impossible: How does one format a string without formatting a string?
I'm going to assume you meant: Without adding a third party dependency.
In which case, if you have doubles (or BigDecimal or float) as input:
String.format("%6.2f", 100.00);
String.format("%6.2f", 10.00);
String.format("%6.2f", 5.00);
(6? Yes; 6! The 6 is the total # of characters to print at minimum. You want 3 digits before the separator, a separator, and 2 digits after, that's a grand total of 6, hence the 6.)
If you have strings as input, evidently you are asking to right-justify them? Well, you can do that:
String.format("%6s", "100.00");
String.format("%6s", "10.00");
String.format("%6s", "5.00");
NB: For convenience, System.out.printf("%6s\n", "100.0"); is short for System.out.println(String.format("%6s", "100.0"));
I want to create a String from a double value with 10 character for example
Double d = 150.23;
The output string like this 0000015023+
I have used this code but it is not working:
String imponibile = String.format("%10d%n", myDoubleValue);
You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:
transform the double number to a int number with the desired rounding and print the int:
int i = (int) Math.round(100.0 * d);
String.format("%010d", i)
Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.
print the double and remove the period from the string afterwards:
String.format("%011.2f", d).replace(".", "")
Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period
I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:
String s = String.format("%+010d", i);
And if you must you can use substring and concatenation to put it at the end:
String imponibile = s.substring(1) + s.charAt(0);
Try f instead of d:
String imponibile = String.format("%010.0f", myDoubleValue*100);
Floating Point - may be applied to Java floating-point types: float,
Float, double, Double, and BigDecimal
Class Formatter
I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);
I am trying to convert a number to two decimal places using Java. Below is what I have tried and it works fine on couple of inputs -
double number = 20.3794;
DecimalFormat df = new DecimalFormat("#.00");
String formattedNumber = df.format(number);
System.out.println(formattedNumber); //output 20.38
Below are my scenarios -
But for this number 20, output I get back as 20.00. In this case, I don't need .00 at the end, it should print out as 20 only.
Similarly for this number 0.019 it prints out .02 so for this I need to have 0 infront of . so 0.02 should get printed out.
Is this possible to do?
you appear to have exchanged # and 0: 0 is for when you wan to force a zero and # is for when the digit is optional.
The pattern "0.##" does exactly what you want.
You can try string format instead with some logic
sample:
double s = 20;
double s2 = 0.019;
String result1 = String.format("%.2f", s);
String result2 = String.format("%.2f", s2);
System.out.println((result1.contains(".00")) ? (int)s : result1);
System.out.println((result2.contains(".00")) ? (int)s : result2);
result:
20
0.02
To get the 0 in front of a number less than 1, change "#" to "0"
To change the whole number printing out to two decimal places, change the two "0" in the decimal places to be "#" so it only prints them if there are numbers other than 0 in those places.
Basically the problem is that your "#" and "0" are reversed. Change the pattern to "0.##" instead of "#.00". The # indicates that a number should only be shown there if it is not 0 (zero shows as absent). The 0 indicates that there will always be a number in that place and it will be 0 if need be. Take a look at the docs.
Here are some examples:
double number1 = 20.3794, number2 = 20, number3 = 0.018, number4 = 20.1;
DecimalFormat df = new DecimalFormat("0.##");
System.out.println(df.format(number1)); // 20.38
System.out.println(df.format(number2)); // 20
System.out.println(df.format(number3)); // 0.02
System.out.println(df.format(number4)); // 20.1
For the 1st case: check if (number % 1 == 0) to see if your double is a whole. In case it was, you can cast it to an integer.
For the 2nd case: Try replacing new DecimalFormat("#.00"); with new DecimalFormat("0.00");
System.out.println(String.format("%.2f",20.3794)); will print 20.38