How to print formatted double value to string in java? - java

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

Related

How to format 18 digit double to become 10 string character

double pdouble= 3.3603335204002837E12;
String pstart= Double.toString(pdouble).replace(".", "") .trim()
String.format("%10d", pstart);
System.out.println("pstart"+pstart);
Can I know why it not works...
It display this:
Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.String at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
.I
Hope anybody can help
%d is for int. As pstart is a String, Use b or s.
String.format("%10s", pstart);
Output
33603335204002837E12
Read Java String format()
However if you need only the first 10 digits from your number, try using DecimalFormat
DecimalFormat d = new DecimalFormat("0000000000");
String number = d.format(pdouble);
Output
3360333520400
This will also add leading 0s if the number is less than 10 digits.
For decimal numbers "f" flag needs to be used.
double pdouble= 3.3603335204002837E12;
System.out.println(String.format("%10f", pdouble));
This will print a string with minimum length of 10 chars.
In this pattern "%10f" the width flag (e.g. 10) is the minimum number of characters
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
from Formatter java doc

how to find length after decimal point of a double number without removing trailing zeroes in java?

Suppose you have a double number say Double d = 12.123223800000.
How can we find length of number from decimal point till the end including all trailing zeroes in it.
Double d = 12.123223800000;
String t = d.toString();
Here it's removing all the trailing zeroes from double number.
Are you able to assign the string directly? Java primitives don't keep trailing zeros because of their binary representation, yet in Mathematics trailing zeros are meaningless .. and so on.
This sample would kinda work
Double d = 12.123223800000;
String str = "12.123223800000"; // d.toString() won't work here
int length = str.length() - str.indexOf(".");
System.out.println(String.format("%."+ length +"f", d));
//prints out - 12.1232238000000
There's no difference between 12.123223800000 and 12.1232238. The trailing zeros are removed while you initialize it to Double. If you still need such solution
String d = "12.123223800000";
System.out.println((d.length()-d.indexOf("."))-1);
This should work:
String text = Double.toString(Math.abs(d))
int decimalPlaces = text.length() - text.indexOf('.') - 1;
There is no way to get the trailing zeros counted because they don't affect the mathematical value of your double figure.
Edit: Except you assign your value directly to a string. With Javas primitve types, it is not possible

Parsing string to double/float throwing errors

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);

Android multiplying double with int [java]

I have a double value a = 0.00059
and an Integer value which gets incremented and multiplied with the double value (say b = 1)
when I set the answer to the textview
//for b = 1
view.setText(((double)(a*b)));
the answer I get is " 5.9E-4 " however it should be 0.00059.
am I multiplying the values correctly.?
In addition to the other answers provided, you can use a formatter:
NumberFormat formatter = new DecimalFormat("#.#####");
view.setText(formatter.format(a*b));
You are multiplying them correctly. The values 5.9E-4 and 0.00059 are equivalent, mathematically and programmatically. The representation 5.9E-4 is like scientific notation, i.e. 5.9x10^(-4) is equivalent to 0.00059.
You get the same value as you want to get, but formatted in a scientific notation. What you need to do is to explicitly convert it to String:
view.setText(String.format("%f", a*b));
And you could eventually specify the number of decimal places to print after the decimal separator in this way:
// displays two digits after the decimal separator
view.setText(String.format("%.2f", a*b));

Java - Format number to print decimal portion only

Is there a simple way in Java to format a decimal, float, double, etc to ONLY print the decimal portion of the number? I do not need the integer portion, even/especially if it is zero!
I am currently using the String.indexOf(".") method combined with the String.substring() method to pick off the portion of the number on the right side of the decimal. Is there a cleaner way to do this? Couldn't find anything in the DecimalFormat class or the printf method. Both always return a zero before the decimal place.
You can remove the integer part of the value by casting the double to a long. You can then subtract this from the original value to be left with only the fractional value:
double val = 3.5;
long intPartVal= (long) val;
double fracPartVal = val - intPartVal;
System.out.println(fracPartVal);
And if you want to get rid of the leading zero you can do this:
System.out.println(("" + fracPartVal).substring(1));
Divide by 1 and get remainder to get decimal portion (using "%"). Use DecimalFormat to format result (using "#" symbol to suppress leading 0s):
double d1 = 67.22;
double d2 = d1%1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d2));
this prints .22
This will print 0.3
double x = 23.8;
int y =(int)x;
float z= (float) (x % y);
System.out.println(z);

Categories