I am trying to format a Number with DecimalFormat. But I want it to format a number, that is like
input: 1234. --> should be formatted to: 1,234.
But I get 1,234.0 or 1,234.00 depending on my rules for the decimal format
What do I have to do in order to get this done?
The methods that should help you are setMinimumFractionDigits and setMaximumFractionDigits.
format.setMinimumFractionDigits(0);
at a guess, is probably what your looking for.
To ensure that the decimal separator is always shown, use: DecimalFormat.setDecimalSeparatorAlwaysShown(true)
You could format the number regardless of whether it is a decimal or not by using
DecimalFormat f = new DecimalFormat("#,###");
f.format(whatever)...
If you don't want to display any decimal places, don't format a floating point value :) If you use BigInteger, int, or long, it should be fine:
import java.math.*;
import java.text.*;
public class Test {
private static final char p = 'p';
public static void main(String[] args) {
NumberFormat format = new DecimalFormat();
BigInteger value = BigInteger.valueOf(1234);
System.out.println(format.format(value));
System.out.println(format.format(1234));
System.out.println(format.format(1234L));
}
}
Try this:
DecimalFormat df = new DecimalFormat("#,###.", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
System.out.println(df.format(1234));
Related
I want to ask how to transform all my String to double with exponential.
when I use the string that length is over seven it's doing fine .
new BigDecimal("12345678").doubleValue() => 1.2345678E7
but seven and under I can't export exponential number.
new BigDecimal("1234567").doubleValue() => 1234567.0
what I want is like 1.234567E6.
Is there any way to do this? I've been searching for a while ,but got nothing.
The problem is the type I return must be double . After transforming the value under seven I can only get the value without exponential.
double test = new BigDecimal("1.234567E6").doubleValue() ;//output 1234567.0
but I need it to be 1.234567E6 and return to caller. Is that Impossible?
You should know that 1.2345678e7 and 12345678.0 are exactly the same value, only with different textual representations. You could represent 1234567.0 as 1.234567e6 too. Also exactly the same double, just a different way of writing it out.
The default output shows values with more than a certain number of significant digits in exponential format ("e-form"), otherwise as plain decimal format.
So you may want to change the formatting of the doubles you receive. This can be done with e.g. DecimalFormat or String.format() or similar. That does not change the doubles, only the way they are presented in a string.
For your problem, you want to convert the value to the BigDecimal with exponential, you can use the DecimalFormat. You can also change the scale for the output value digits.
import java.math.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
double a = new BigDecimal("1234567").doubleValue();
String b;
System.out.println(a);
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.DOWN);
formatter.setMinimumFractionDigits(5); //<---Scale
b = formatter.format(a);
System.out.println(b);
}
}
The output will be like:
1234567.0 //Unformatted Value
1.23456E6 //Formatted Value
See the section about Scientific Notation in java.text.DecimalFormat.
For example,
DecimalFormat scientificFormat = new DecimalFormat("0.###E0");
System.out.println(scientificFormat.format(BigDecimal.valueOf(123456L)));
System.out.println(scientificFormat.format(BigDecimal.valueOf(1234567L)));
scientificFormat.setMinimumFractionDigits(10);
System.out.println(scientificFormat.format(BigDecimal.valueOf(12345678L)));
would give you
1,235E5
1,235E6
1,2345678000E7
Change the pattern to match what you're looking for.
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.
Why does it not round in the parsing process?
NumberFormat format = NumberFormat.getInstance();
System.out.println(format.getMaximumFractionDigits());// 3
System.out.println(format.getRoundingMode());// half even
Double dob = (Double)format.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
The digit counts are only used for formatting. When you parse a number you always get the number that best matches the input, even if it has more digits than the NumberFormat would use to format.
To parse a number from a string and then round to a given number of fractional digits you can use BigDecimal from the java.math package:
BigDecimal bd = BigDecimal("1212.35656");
double dob = bd.setScale(3, RoundingMode.HALF_EVEN).doubleValue();
To obtain what you desire you need to call the formatter metod of the implementation NumberFormat loaded (in your case DecimalFromat); i just added the needed lines at the end and wrapped in a main:
import java.text.NumberFormat;
public class NumberFormatRounding {
public static void main(String[] args) throws Exception{
NumberFormat formatter = NumberFormat.getInstance();
System.out.println(formatter.getMaximumFractionDigits());// 3
System.out.println(formatter.getRoundingMode());// half even
Double dob = (Double) formatter.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
String formattedDob = formatter.format(dob.doubleValue());
System.out.println(formattedDob);// output is 1212.357
}
}
Note that the formattedDob is a String
All Experts
I am doing some logical stuff in my program with an variable of type double.
everything is Ok when the value of type double parameter is less then 1,00,00,000.
But when the value of it becomes > one Crores it is automatically converted in to an exponetial form and i got an exception .
For Example
Value 10010001.25 becomes
1.001000125E7
I want the value is in normal form .
Any help ??
Thank You
Mihir Parekh
I would recommend using System.out.println(new BigDecimal(d)).
Here is a comparison of some alternatives:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
double d = 10010001.125;
// 10010001.125000 (lots of trailing zeroes)
System.out.printf("%f%n", d);
// 10010001.13 (perhaps not what you want)
System.out.printf("%.2f%n", d);
// 10010001.12 (not accurate in my opinion)
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(d));
// 10010001.125 (all relevant digits, and no trailing zeroes)
System.out.println(new BigDecimal(d));
}
}
The double is a binary format. The two formats you see are different ways of converting a double into a String. You can try DecimalFormat to convert a number into a decimal formatted String.
However you might find this simpler
double d = 10010001.25;
System.out.printf("%.2f%n", d);
prints
10010001.25
EDIT:
System.out.printf("%,.2f%n", d);
prints
10,010,001.25
You can use DecimalFormat
double d = 10010001.25;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
How to convert a string 0E-11 to 0.00000000000 in Java? I want to display the number in non scientific notations. I've tried looking at the number formatter in Java, however I need to specific the exact number of decimals I want but I will not always know. I simply want the number of decimal places as specificed by my original number.
Apparently the correct answer is to user BigDecimal and retrieve the precision and scale numbers. Then use those numbers in the Formatter. Something similar like this:
BigDecimal bg = new BigDecimal(rs.getString(i));
Formatter fmt = new Formatter();
fmt.format("%." + bg.scale() + "f", bg);
buf.append( fmt);
Using BigDecimal:
public static String removeScientificNotation(String value)
{
return new BigDecimal(value).toPlainString();
}
public static void main(String[] arguments) throws Exception
{
System.out.println(removeScientificNotation("3.0103E-7"));
}
Prints:
0.00000030103
I would use BigDecimal.Pass your string into it as a parameter and then use String.format to represent your newly created BigDecimal without scientific notation.
Float or Double classes can be used too.
double d = Double.parseDouble("7.399999999999985E-5");
NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(d);
System.out.println(f); // output --> 0.00007
I haven't tried it, but java.text.NumberFormat might do what you want.