I want to add zero before decimal, if the number starts with decimal itself.
Input: .2345
Output: 0.2345
I'm using DecimalForamtter. I'm avoiding using string appender.
Please suggest.
Thank You
that should give you the expected output:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
DecimalFormat lFormatter = new DecimalFormat("##0.0000");
String lOutput = lFormatter.format(value);
Assert.assertTrue(lOutput.startsWith("0."));
}
or with String.format:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
String lOutput = String.format("%.20f", value);
Assert.assertTrue(lOutput.startsWith("0."));
double value2 = .1221313d;
String lOutput2 = String.format("%.20d", value2);
Assert.assertTrue(lOutput2.startsWith("0."));
}
I think you are using Float right? Otherwise you have to replace f with d for Double.
I have used below code and worked in all scenarios. I wanted to get 10 digits including 2 decimal places. It will give me trailing 0s in decimal place also.
DecimalFormat df = new DecimalFormat("00000000.00");
double d1 = 678.90;
System.out.println(df.format(d1));
Output: 00000678.90
Related
I retrieve from an XML file a float number that I want to format and insert in a text file with the pattern 8 digits after comma, and 2 before.
Here is my code:
String patternNNDotNNNNNNNN = "%11.8f";
float value = 1.70473711f;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, value);
System.out.println(result);
As a result I get: 1.70473707
Same problem if I use:
java.text.DecimalFormatSymbols symbols = new java.text.DecimalFormatSymbols(java.util.Locale.US);
java.text.DecimalFormat df = new java.text.DecimalFormat("##.########", symbols);
System.out.println(df.format(value));
I don't understand why I have a rounded value (1.70473711 comes to 1.70473707).
This is because the precision of the float means that the value 1.7043711 is not actually 1.7043711.
Consider the following which process 1.70473711f as both a float and a double:
String patternNNDotNNNNNNNN = "%11.8f";
float valueF = 1.70473711f;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueF);
System.out.println(valueF);
System.out.println(result);
double valueD = 1.70473711f;
result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueD);
System.out.println(valueD);
System.out.println(result);
Output:
1.7047371
1.70473707
1.7047370672225952
1.70473707
When treating the value as a double, you can see that 1.7043711f is actually 1.7047370672225952. Rounding that to 8 places gives 1.70473707 and not 1.70473711 as expected.
Instead, treat the number as a double (i.e. remove the f) and the increase precision will result in the expected output:
double valueD = 1.70473711;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueD);
System.out.println(valueD);
System.out.println(result);
Output:
1.70473711
1.70473711
String.format on floating point values does round them. If you don't want that, use BigDecimal. See
double d = 0.125;
System.out.printf("%.2f%n", d);
I'm trying to take a string and convert into a currency. For example I would like to take the string 12579500 and convert it to $125,795.00. I am trying to use DecimalFormat("$#,###.00), to convert the string after I turn it into a double, but what I'm winding up with is $12,579,500.00.
How do I set the last 2 numbers at the end of the string to be decimal points?
Here is my code so far.
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice);
System.out.print(df.format(ticketPriceNum));
This will make sure that your string is reduced by 2 characters
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice.substring(0, ticketPrice.length()- 2));
System.out.print(df.format(ticketPriceNum));
try this please
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$#,###,##.00");
//if last two digits of ticketprice should be decimal points
double ticketPriceNum = Double.parseDouble(ticketPrice/100);
System.out.println(df.format(ticketPriceNum ));
}
I'm still new to Java and I was wondering if there are any ways to format to a double without having it rounded?
Example:
double n = 0.12876543;
String s = String.format("%1$1.2f", n);
If I were to print to the system, it would return the 0.13 instead of the precise 0.12. Now I have thought of a solution but I want to know if there is a better way of doing this. This my simple solution:
double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f", n));
Any other thoughts or solutions?
An elegant solution would be to use setRoundingMode with DecimalFormat. It sets the RoundingMode appropriately.
For example:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));
Output:
0.12
Further, if you want to do additional formatting as a string you can always change the double value into string:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);
Output:
0.12
Please refer similar solution here: https://stackoverflow.com/a/8560708/4085019
As is, rounded to 2 decimals and truncated to 2 decimals :
double n = 0.12876543;
String complete = String.valueOf(n);
System.out.println(complete);
DecimalFormat df = new DecimalFormat("#.##");
String rounded = df.format(n);
System.out.println(rounded);
df.setRoundingMode(RoundingMode.DOWN);
String truncated = df.format(n);
System.out.println(truncated);
it displays :
0.12876543
0.13
0.12
Your example is working correctly in that it is properly rounding the number to 2 decimal places. 0.12876543 properly rounds to 0.13 when rounded to 2 decimal places. However, it seems like you always want to round the number down? If that is the case then you can do something like this...
public static void main(String[] args) throws IOException, InterruptedException {
double n = 0.12876543;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.DOWN);
String s = df.format(n);
System.out.println(s);
}
This will print out a value of 0.12
Note first that a double is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal, which has a setScale() method for truncation, or use DecimalFormat to get a String.
I am trying to figure out how to, given a decimal through a String calculate the number of significant digits so that I can do a calculation to the decimal and print the result with the same number of significant digits. Here's an SSCCE:
import java.text.DecimalFormat;
import java.text.ParseException;
public class Test {
public static void main(String[] args) {
try {
DecimalFormat df = new DecimalFormat();
String decimal1 = "54.60"; // Decimal is input as a string with a specific number of significant digits.
double d = df.parse(decimal1).doubleValue();
d = d * -1; // Multiply the decimal by -1 (this is why we parsed it, so we could do a calculatin).
System.out.println(df.format(d)); // I need to print this with the same # of significant digits.
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I know DecimalFormat is to 1) tell the program how you intend your decimal to be displayed (format()) and 2) to tell the program what format to expect a String-represented decimal to be in (parse()). But, is there a way to DEDUCE the DecimalFormat from a parsed string and then use that same DecimalFormat to output a number?
Use BigDecimal:
String decimal1 = "54.60";
BigDecimal bigDecimal = new BigDecimal(decimal1);
BigDecimal negative = bigDecimal.negate(); // negate keeps scale
System.out.println(negative);
Or the short version:
System.out.println((new BigDecimal(decimal1)).negate());
Find it via String.indexOf('.').
public int findDecimalPlaces (String input) {
int dot = input.indexOf('.');
if (dot < 0)
return 0;
return input.length() - dot - 1;
}
You can also configure a DecimalFormat/ NumberFormat via setMinimumFractionDigits() and setMaximumFractionDigits() to set an output format, rather than having to build the pattern as a string.
int sigFigs = decimal1.split("\\.")[1].length();
Computing the length of the string to the right of the decimal is probably the easiest method of achieving your goal.
If you want decimal places, you can't use floating-point in the first place, as FP doesn't have them: FP has binary places. Use BigDecimal, and construct it directly from the String. I don't see why you need a DecimalFormat object at all.
You could convert a number string to a format string using regex:
String format = num.replaceAll("^\\d*", "#").replaceAll("\\d", "0");
eg "123.45" --> "#.00" and "123" --> "#"
Then use the result as the pattern for a DecimalFormat
Not only does it work, it's only one line.
Please help me to solve this. I trying to get value from textview and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code
String value = tvInput.getText().toString();
\\tvInput is my textView
Double result = 0.0;
Double input1=0.0;
Double input2=0.0;
input=Double.parseDouble(value);
result = input1 + input2;
tvInput.setText(Double.toString(result));
if i give input1 value as 1234567 and input2 as 1234567 i am getting correct result but if give input1 as 12345678 and input2 as 3. the output is 1.2345681E7
The value you get is correct, the issue is with the way you print it.
You're relying on toString for a double output; if you want to guarantee not to have an exponential notation, you should format it using a DecimalFormat, or with String.format;
DecimalFormat myFormatter = new DecimalFormat("############");
tvInput.setText(myFormatter.format(result));
Also see the format documentation
The behavior you describe is consistent with the javadoc. You could use String.format instead.
Either 12345678 and 1.2345678E7 are exactly the same number. No trouble with that
Your trouble is with the representation, if E>6 then toString() use scientific notation. You may want to use NumberFormat for this.
Use String.format: example
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String i1 = "12345678";
String i2 = "3";
double d1 = Double.parseDouble(i1);
double d2 = Double.parseDouble(i2);
double d = d1 + d2;
System.out.println( String.format("%f", d) );
}
}
Why don't use Integer instead?
String value = tvInput.getText().toString();
\\tvInput is my textView
int result = 0;
int input1 = 0;
int input2 = 0;
input=Integer.parseInt(value);
result = input1 + input2;
tvInput.setText(Integer.toString(result));