java (beginner) converting scientific notation to decimal - java

if
double d = 1.999e-4
I want my output to be 0.0001999.
How can I do it?

NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(d);
You can explore the sub classes of NumberFormat class to know more details.

I suppose there is a method in BigDecimal Class called toPlainString().
e.g. if the the BigDecimal is 1.23e-8 then the method returns 0.0000000124.
BigDecimal d = new BigDecimal("1.23E-8");
System.out.println(d.toPlainString());
Above code prints 0.0000000123, then you can process the string as per your requirement.

You can do it like this:
double d = 1.999e-4;
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(7);
System.out.println(nf.format(d));
Check out the documentation of NumberFormat's methods to format your double as you see fit.
DecimalFormat is a special case of NumberFormat as its constructor states, I don't think that you need its functionality for your case. Check out their documentation if you are confused. Use the factory method getInstance() of NumberFormat for your convenience.

If all you want is to print like that.
System.out.printf("%1$.10f", d);
you can change 10f, 10=number of decimal places you want.

Take a look over
java.text.DecimalFormat
and
java.text.DecimalFormatSymbols

Related

Convert double value to contain decimal seperator and only two digits after comma in groovy

I would like to convert a number such as the following:
2937998.7397271004
to look like this:
2.937.998,73
My attempt of achieving this looks as following, but the result still looks the same:
DecimalFormat decimalFormat = new DecimalFormat("###.###.###.###,00");
def val = decimalFormat.format(cell.getNumericCellValue().doubleValue())
return val
One way to do is to use a locale which supports your formatting pattern. For example Locale.GERMAN is in line with what you are expecting
DecimalFormat df = new DecimalFormat("###,###.00",
DecimalFormatSymbols.getInstance(Locale.GERMAN));
df.format(2937998.7397271004); // 2.937.998,74
You should definitely use Locale for this issue. And in your case formatting is german:
import java.text.NumberFormat
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMAN);
println numberFormat.format(2937998.7397271004)
Although I am not familiar with groovy as far as I know it still utilizes the java libraries.
You cannot utilize multipled .'s on a standard DecimalFormat as can be seen in the documentation for the java class: Documentation.
So the following line of code needs to changed to:
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
Which will respond with 2.937.998,74 utilizing the provided value of 2937998.7397271004.
If you want to do it as 2.937.998,74 you can, again at least in java, do the following.
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
DecimalFormatSymbols custom = new DecimalFormatSymbols();
custom.setDecimalSeparator(',');
custom.setGroupingSeparator('.');
decimalFormat.setDecimalFormatSymbols(custom);
String val = decimalFormat.format(cell.getNumericCellValue().doubleValue());
Or use the locale as other aswers sugest.

DecimalFormat is returning -0.00

This bit of code
DecimalFormat formatter = new DecimalFormat("0.00");
return formatter.format(-0.001);
returns
"-0.00"
I would really prefer (and expect) "0.00"
I know I can fix this by writing a subclass of DecimalFormat, but is there a way to do this using the standard DecimalFormat?
EDIT: I only wan't to change the particular case where the result is "-0.00". All other negative values should remain unchanged, eg: -9.1 -> "-9.10"
You could test the string when it's returned.
I don't believe formatting will manipulate the value.
It can only format it. Perhaps you can round it first, and then format it?
DecimalFormat formatter = new DecimalFormat("0.00");
double x = -0.001;
double y = Math.round(x*100.0)/100.0;
return formatter.format(y);

Stop second zero from being cut off in Java program [duplicate]

I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?
One of the way would be using NumberFormat.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
Output:
4.00
With Java 8, you can use format method..: -
System.out.format("%.2f", 4.0); // OR
System.out.printf("%.2f", 4.0);
f is used for floating point value..
2 after decimal denotes, number of decimal places after .
For most Java versions, you can use DecimalFormat: -
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by Locale.getDefault().
Using String.format, you can do this:
double price = 52000;
String.format("$%,.2f", price);
Notice the comma which makes this different from #Vincent's answer
Output:
$52,000.00
A good resource for formatting is the official java page on the subject
You could always use the static method printf from System.out - you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.
Ex:
System.out.format("%.4f %n", 4.0);
System.out.printf("%.2f %n", 4.0);
Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).
double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
new DecimalFormat("#0.00").format(4.0d);
An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.
Here you basically specify how many numbers you want to appear after the decimal point.
So an input of 4.0 would produce 4.00, assuming your specified amount was 2.
But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down
For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));
Try it online
There are many way you can do this. Those are given bellow:
Suppose your original number is given bellow:
double number = 2354548.235;
Using NumberFormat:
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(number));
Using String.format:
System.out.println(String.format("%,.2f", number));
Using DecimalFormat and pattern:
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(number);
System.out.println(fString);
Using DecimalFormat and pattern
DecimalFormat decimalFormat = new DecimalFormat("############.##");
BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
System.out.println(formattedOutput);
In all cases the output will be:
2354548.23
Note:
During rounding you can add RoundingMode in your formatter. Here are some rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
First import NumberFormat. Then add this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
This will give you two decimal places and put a dollar sign if it's dealing with currency.
import java.text.NumberFormat;
public class Payroll
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int hoursWorked = 80;
double hourlyPay = 15.52;
double grossPay = hoursWorked * hourlyPay;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
}
}
You can do it as follows:
double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00
The simplest way is just to use replace.
String var = "X,00";
String newVar = var.replace(",",".");
The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:
Double var = Double.parseDouble(("X,00").replace(",",".");
I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.

Recommended way to format numbers in a locale aware way?

Lets assume we have one million.
In English it should be formatted as 1,000,000 in German it should be 1.000.000.
Using NumberFormat class:
For English:
NumberFormat nf_us = NumberFormat.getInstance(Locale.US);
String number_us = nf_us.format(1000000);
For German:
NumberFormat nf_ge = NumberFormat.getInstance(Locale.GERMAN);
String number_ge = nf_ge.format(1000000);
You can use NumberFormat.
Android documentation is quite clear on it.
You can achieve this with using the NumberFormat class, this also allows you to parse Strings into a local aware number.
NumberFormat formatter = NumberFormat.getInstance(Locale.GERMAN);
String localeFormattedNumber = formatter.format(1000000);

How to convert a string 3.0103E-7 to 0.00000030103 in Java?

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.

Categories