Related
I am invoking a method called "calculateStampDuty", which will return the
amount of stamp duty to be paid on a property. The percentage calculation works
fine, and returns the correct value of "15000.0". However, I want to display the value to
the front end user as just "15000", so just want to remove the decimal and any preceding values
thereafter. How can this be done? My code is below:
float HouseValue = 150000;
double percentageValue;
percentageValue = calculateStampDuty(10, HouseValue);
private double calculateStampDuty(int PercentageIn, double HouseValueIn){
double test = PercentageIn * HouseValueIn / 100;
return test;
}
I have tried the following:
Creating a new string which will convert the double value to a string, as per below:
String newValue = percentageValue.toString();
I have tried using the 'valueOf' method on the String object, as per below:
String total2 = String.valueOf(percentageValue);
However, I just cannot get a value with no decimal places. Does anyone know
in this example how you would get "15000" instead of "15000.0"?
Thanks
Nice and simple. Add this snippet in whatever you're outputting to:
String.format("%.0f", percentageValue)
You can convert the double value into a int value.
int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
I did this to remove the decimal places from the double value
new DecimalFormat("#").format(100.0);
The output of the above is
100
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
You can convert double,float variables to integer in a single line of code using explicit type casting.
float x = 3.05
int y = (int) x;
System.out.println(y);
The output will be 3
I would try this:
String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.
int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Try this you will get a string from the format method.
DecimalFormat df = new DecimalFormat("##0");
df.format((Math.round(doubleValue * 100.0) / 100.0));
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Use
Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)
the simple way to remove
new java.text.DecimalFormat("#").format(value)
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.
String newValue = ((int) percentageValue).toString();
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose
The problem is two fold-
To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
Double i = Double.parseDouble("String with double value");
Log.i(tag, "display double " + i);
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); // set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]", "");
Double i = Double.parseDouble(result);
int max = Integer.parseInt(result);
} catch (Exception e) {
System.out.println("ex=" + e);
}
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
This should do the trick.
System.out.println(percentageValue.split("\\.")[0]);
Try:
String newValue = String.format("%d", (int)d);
I want to print a double value in Java without exponential form.
double dexp = 12345678;
System.out.println("dexp: "+dexp);
It shows this E notation: 1.2345678E7.
I want it to print it like this: 12345678
What is the best way to prevent this?
Java prevent E notation in a double:
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?
http://youtube.com/watch?v=PZRI1IfStY0
You could use printf() with %f:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
This will print dexp: 12345678.000000. If you don't want the fractional part, use
System.out.printf("dexp: %.0f\n", dexp);
0 in %.0f means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the documentation.
The default toString() format used in your original code is spelled out here.
In short:
If you want to get rid of trailing zeros and Locale problems, then you should use:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
System.out.println(df.format(myValue)); // Output: 0.00000021
Explanation:
Why other answers did not suit me:
Double.toString() or System.out.println or FloatingDecimal.toJavaFormatString uses scientific notations if double is less than 10^-3 or greater than or equal to 10^7
By using %f, the default decimal precision is 6, otherwise you can hardcode it, but it results in extra zeros added if you have fewer decimals. Example:
double myValue = 0.00000021d;
String.format("%.12f", myvalue); // Output: 0.000000210000
By using setMaximumFractionDigits(0); or %.0f you remove any decimal precision, which is fine for integers/longs, but not for double:
double myValue = 0.00000021d;
System.out.println(String.format("%.0f", myvalue)); // Output: 0
DecimalFormat df = new DecimalFormat("0");
System.out.println(df.format(myValue)); // Output: 0
By using DecimalFormat, you are local dependent. In French locale, the decimal separator is a comma, not a point:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0");
df.setMaximumFractionDigits(340);
System.out.println(df.format(myvalue)); // Output: 0,00000021
Using the ENGLISH locale makes sure you get a point for decimal separator, wherever your program will run.
Why using 340 then for setMaximumFractionDigits?
Two reasons:
setMaximumFractionDigits accepts an integer, but its implementation has a maximum digits allowed of DecimalFormat.DOUBLE_FRACTION_DIGITS which equals 340
Double.MIN_VALUE = 4.9E-324 so with 340 digits you are sure not to round your double and lose precision.
You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:
double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678
I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:
this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.
It looks like this in its shortest form:
return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
NaN and infinite values have to be checked extra, so looks like this in its complete form:
public static String doubleToString(Double d) {
if (d == null)
return null;
if (d.isNaN() || d.isInfinite())
return d.toString();
return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}
This can also be copied/pasted to work nicely with Float.
For Java 7 and below, this results in "0.0" for any zero-valued Doubles, so you would need to add:
if (d.doubleValue() == 0)
return "0";
Java/Kotlin compiler converts any value greater than 9999999 (greater than or equal to 10 million) to scientific notation ie. Epsilion notation.
Ex: 12345678 is converted to 1.2345678E7
Use this code to avoid automatic conversion to scientific notation:
fun setTotalSalesValue(String total) {
var valueWithoutEpsilon = total.toBigDecimal()
/* Set the converted value to your android text view using setText() function */
salesTextView.setText( valueWithoutEpsilon.toPlainString() )
}
This will work as long as your number is a whole number:
double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
If the double variable has precision after the decimal point it will truncate it.
I needed to convert some double to currency values and found that most of the solutions were OK, but not for me.
The DecimalFormat was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc.) - without any decimal point.
And if it's decimal, I get only two decimal digits.
I think everyone had the right idea, but all answers were not straightforward.
I can see this being a very useful piece of code. Here is a snippet of what will work:
System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));
the ".8" is where you set the number of decimal places you would like to show.
I am using Eclipse and it worked no problem.
Hope this was helpful. I would appreciate any feedback!
The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.
static String convertFromScientificNotation(double number) {
// Check if in scientific notation
if (String.valueOf(number).toLowerCase().contains("e")) {
System.out.println("The scientific notation number'"
+ number
+ "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
NumberFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(25);
return formatter.format(number);
} else
return String.valueOf(number);
}
This may be a tangent.... but if you need to put a numerical value as an integer (that is too big to be an integer) into a serializer (JSON, etc.) then you probably want "BigInterger"
Example:
value is a string - 7515904334
We need to represent it as a numerical in a Json message:
{
"contact_phone":"800220-3333",
"servicer_id":7515904334,
"servicer_name":"SOME CORPORATION"
}
We can't print it or we'll get this:
{
"contact_phone":"800220-3333",
"servicer_id":"7515904334",
"servicer_name":"SOME CORPORATION"
}
Adding the value to the node like this produces the desired outcome:
BigInteger.valueOf(Long.parseLong(value, 10))
I'm not sure this is really on-topic, but since this question was my top hit when I searched for my solution, I thought I would share here for the benefit of others, lie me, who search poorly. :D
use String.format ("%.0f", number)
%.0f for zero decimal
String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);
I had this same problem in my production code when I was using it as a string input to a math.Eval() function which takes a string like "x + 20 / 50"
I looked at hundreds of articles... In the end I went with this because of the speed. And because the Eval function was going to convert it back into its own number format eventually and math.Eval() didn't support the trailing E-07 that other methods returned, and anything over 5 dp was too much detail for my application anyway.
This is now used in production code for an application that has 1,000+ users...
double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp
s display as: 0.00021
This will work not only for a whole numbers:
double dexp = 12345678.12345678;
BigDecimal bigDecimal = new BigDecimal(Double.toString(dexp));
System.out.println("dexp: "+ bigDecimal.toPlainString());
My solution:
String str = String.format ("%.0f", yourDouble);
For integer values represented by a double, you can use this code, which is much faster than the other solutions.
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others, this is the best
DecimalFormat df =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
return df.format(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
This works for me. The output will be a String.
String.format("%.12f", myvalue);
Good way to convert scientific e notation
String.valueOf(YourDoubleValue.longValue())
I want to print a double value in Java without exponential form.
double dexp = 12345678;
System.out.println("dexp: "+dexp);
It shows this E notation: 1.2345678E7.
I want it to print it like this: 12345678
What is the best way to prevent this?
Java prevent E notation in a double:
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?
http://youtube.com/watch?v=PZRI1IfStY0
You could use printf() with %f:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
This will print dexp: 12345678.000000. If you don't want the fractional part, use
System.out.printf("dexp: %.0f\n", dexp);
0 in %.0f means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the documentation.
The default toString() format used in your original code is spelled out here.
In short:
If you want to get rid of trailing zeros and Locale problems, then you should use:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
System.out.println(df.format(myValue)); // Output: 0.00000021
Explanation:
Why other answers did not suit me:
Double.toString() or System.out.println or FloatingDecimal.toJavaFormatString uses scientific notations if double is less than 10^-3 or greater than or equal to 10^7
By using %f, the default decimal precision is 6, otherwise you can hardcode it, but it results in extra zeros added if you have fewer decimals. Example:
double myValue = 0.00000021d;
String.format("%.12f", myvalue); // Output: 0.000000210000
By using setMaximumFractionDigits(0); or %.0f you remove any decimal precision, which is fine for integers/longs, but not for double:
double myValue = 0.00000021d;
System.out.println(String.format("%.0f", myvalue)); // Output: 0
DecimalFormat df = new DecimalFormat("0");
System.out.println(df.format(myValue)); // Output: 0
By using DecimalFormat, you are local dependent. In French locale, the decimal separator is a comma, not a point:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0");
df.setMaximumFractionDigits(340);
System.out.println(df.format(myvalue)); // Output: 0,00000021
Using the ENGLISH locale makes sure you get a point for decimal separator, wherever your program will run.
Why using 340 then for setMaximumFractionDigits?
Two reasons:
setMaximumFractionDigits accepts an integer, but its implementation has a maximum digits allowed of DecimalFormat.DOUBLE_FRACTION_DIGITS which equals 340
Double.MIN_VALUE = 4.9E-324 so with 340 digits you are sure not to round your double and lose precision.
You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:
double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678
I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:
this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.
It looks like this in its shortest form:
return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
NaN and infinite values have to be checked extra, so looks like this in its complete form:
public static String doubleToString(Double d) {
if (d == null)
return null;
if (d.isNaN() || d.isInfinite())
return d.toString();
return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}
This can also be copied/pasted to work nicely with Float.
For Java 7 and below, this results in "0.0" for any zero-valued Doubles, so you would need to add:
if (d.doubleValue() == 0)
return "0";
Java/Kotlin compiler converts any value greater than 9999999 (greater than or equal to 10 million) to scientific notation ie. Epsilion notation.
Ex: 12345678 is converted to 1.2345678E7
Use this code to avoid automatic conversion to scientific notation:
fun setTotalSalesValue(String total) {
var valueWithoutEpsilon = total.toBigDecimal()
/* Set the converted value to your android text view using setText() function */
salesTextView.setText( valueWithoutEpsilon.toPlainString() )
}
This will work as long as your number is a whole number:
double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
If the double variable has precision after the decimal point it will truncate it.
I needed to convert some double to currency values and found that most of the solutions were OK, but not for me.
The DecimalFormat was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc.) - without any decimal point.
And if it's decimal, I get only two decimal digits.
I think everyone had the right idea, but all answers were not straightforward.
I can see this being a very useful piece of code. Here is a snippet of what will work:
System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));
the ".8" is where you set the number of decimal places you would like to show.
I am using Eclipse and it worked no problem.
Hope this was helpful. I would appreciate any feedback!
The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.
static String convertFromScientificNotation(double number) {
// Check if in scientific notation
if (String.valueOf(number).toLowerCase().contains("e")) {
System.out.println("The scientific notation number'"
+ number
+ "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
NumberFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(25);
return formatter.format(number);
} else
return String.valueOf(number);
}
This may be a tangent.... but if you need to put a numerical value as an integer (that is too big to be an integer) into a serializer (JSON, etc.) then you probably want "BigInterger"
Example:
value is a string - 7515904334
We need to represent it as a numerical in a Json message:
{
"contact_phone":"800220-3333",
"servicer_id":7515904334,
"servicer_name":"SOME CORPORATION"
}
We can't print it or we'll get this:
{
"contact_phone":"800220-3333",
"servicer_id":"7515904334",
"servicer_name":"SOME CORPORATION"
}
Adding the value to the node like this produces the desired outcome:
BigInteger.valueOf(Long.parseLong(value, 10))
I'm not sure this is really on-topic, but since this question was my top hit when I searched for my solution, I thought I would share here for the benefit of others, lie me, who search poorly. :D
use String.format ("%.0f", number)
%.0f for zero decimal
String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);
I had this same problem in my production code when I was using it as a string input to a math.Eval() function which takes a string like "x + 20 / 50"
I looked at hundreds of articles... In the end I went with this because of the speed. And because the Eval function was going to convert it back into its own number format eventually and math.Eval() didn't support the trailing E-07 that other methods returned, and anything over 5 dp was too much detail for my application anyway.
This is now used in production code for an application that has 1,000+ users...
double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp
s display as: 0.00021
This will work not only for a whole numbers:
double dexp = 12345678.12345678;
BigDecimal bigDecimal = new BigDecimal(Double.toString(dexp));
System.out.println("dexp: "+ bigDecimal.toPlainString());
My solution:
String str = String.format ("%.0f", yourDouble);
For integer values represented by a double, you can use this code, which is much faster than the other solutions.
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others, this is the best
DecimalFormat df =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
return df.format(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
This works for me. The output will be a String.
String.format("%.12f", myvalue);
Good way to convert scientific e notation
String.valueOf(YourDoubleValue.longValue())
How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?
I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"
double d = 9.01236789E9;
System.out.println(BigDecimal.valueOf(d).toPlainString());
While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.
If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
double value = 9.01236789E9;
String text = String.format("%.0f", value);
System.out.println(text); // 9012367890
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
format.setGroupingUsed(false);
System.out.println(format.format(value)); // 9012367890
}
}
Try String.format("%20.0f", 9.01236789E9)
Note though it's never an exact value, so "preserving every digit" doesn't really make sense.
You can use it.
String doubleString = Double.toString(inValue)
inValue -----> Described by you.to what position you want to Change double to a string.
In this case, you can also do
double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890
I'd like to use Java's DecimalFormat to format doubles like so:
#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41
The best I can come up with so far is:
new DecimalFormat("'$'0.##");
But this doesn't work for case #2, and instead outputs "$100.5"
Edit:
A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".
Does it have to use DecimalFormat?
If not, it looks like the following should work:
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
Use NumberFormat:
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);
Also, don't use doubles to represent exact values. If you're using currency values in something like a Monte Carlo method (where the values aren't exact anyways), double is preferred.
See also: Write Java programs to calculate and format currency
Try
new DecimalFormat("'$'0.00");
Edit:
I Tried
DecimalFormat d = new DecimalFormat("'$'0.00");
System.out.println(d.format(100));
System.out.println(d.format(100.5));
System.out.println(d.format(100.41));
and got
$100.00
$100.50
$100.41
Try using
DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);
You can check "is number whole or not" and choose needed number format.
public class test {
public static void main(String[] args){
System.out.println(function(100d));
System.out.println(function(100.5d));
System.out.println(function(100.42d));
}
public static String function(Double doubleValue){
boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
formatSymbols.setDecimalSeparator('.');
String pattern= isWholeNumber ? "#.##" : "#.00";
DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
return df.format(doubleValue);
}
}
will give exactly what you want:
100
100.50
100.42
You can use the following format:
DecimalFormat dformat = new DecimalFormat("$#.##");
I know its too late. However following worked for me :
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);
\u00A4 : acts as a placeholder for currency symbol
#######0.00 : acts as a placeholder pattern for actual number with 2 decimal
places precision.
Hope this helps whoever reads this in future :)
You can try by using two different DecimalFormat objects based on the condition as follows:
double d=100;
double d2=100.5;
double d3=100.41;
DecimalFormat df=new DecimalFormat("'$'0.00");
if(d%1==0){ // this is to check a whole number
DecimalFormat df2=new DecimalFormat("'$'");
System.out.println(df2.format(d));
}
System.out.println(df.format(d2));
System.out.println(df.format(d3));
Output:-
$100
$100.50
$100.41
You could use the Java Money API to achieve this. (although this is not using DecialFormat)
long amountInCents = ...;
double amountInEuro = amountInCents / 100.00;
String customPattern;
if (minimumOrderValueInCents % 100 == 0) {
customPattern = "# ¤";
} else {
customPattern = "#.## ¤";
}
Money minDeliveryAmount = Money.of(amountInEuro, "EUR");
MonetaryAmountFormat formatter = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.GERMANY)
.set(CurrencyStyle.SYMBOL)
.set("pattern", customPattern)
.build());
System.out.println(minDeliveryAmount);
printf also works.
Example:
double anyNumber = 100;
printf("The value is %4.2f ", anyNumber);
Output:
The value is 100.00
4.2 means force the number to have two digits after the decimal. The 4 controls how many digits to the right of the decimal.