In Objective C I have been using this code to format a value so that a value with zero decimals will be written without decimals and a value with decimals will be written with one decimal:
CGFloat value = 1.5;
return [NSString stringWithFormat:#"%.*f",(value != floor(value)),value];
//If value == 1.5 the output will be 1.5
//If value == 1.0 the output will be 1
I need to do the same thing for a double value in Java, I tried the following but that is not working:
return String.format("%.*f",(value != Math.floor(value)),value);
Look at how to print a Double without commas. This will definitely provide you some idea.
Precisely, this will do
DecimalFormat.getInstance().format(1.5)
DecimalFormat.getInstance().format(1.0)
Do you mean something like?
return value == (long) value ? ""+(long) value : ""+value;
Not sure how to do it with String.format("..") method, but you can achieve the same using java.text.DecimalFormat; See this code sample:
import java.text.NumberFormat;
import java.text.DecimalFormat;
class Test {
public static void main(String... args) {
NumberFormat formatter = new DecimalFormat();
System.out.println(formatter.format(1.5));
System.out.println(formatter.format(1.0));
}
}
The output is 1.5 and 1 respectively.
Related
I wanted to convert a number which is in string format to a percentage value with one decimal point. Below is my sample input and expected output.
Expected results:
"0.0195" => "2.0%"
"0.0401" => "4.0%"
I know this may be a simple question but I am not able to find the exact solution for this using java APIs, I tried all the rounding modes present under RoundingMode enum, but no rounding mode gives my expected result. Could you please help, I may be missing something.
import java.math.RoundingMode;
import java.text.NumberFormat;
public class RoundingModeExample {
public static void main(String[] args) {
System.out.println(formatPercentage("0.0195") + "(expected 2.0%)");
System.out.println(formatPercentage("0.0401") + "(expected 4.0%)");
}
private static String formatPercentage(String number) {
String formattedValue = "";
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(1);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
try {
formattedValue = numberFormat.format(Double.valueOf(number));
} catch (NumberFormatException e) {
formattedValue = number;
}
return formattedValue;
}
}
Output of the above program:
1.9%(expected 2.0%)
4.0%(expected 4.0%)
The problem with 0.0195 is that there is no double precision number that is exactly mathematically equal to it. When you write 0.0195 in program source code or parse the string "0.0195" into double, the number you get is actually a little bit less. That's why the formatter rounds it to 1.9%.
You can get around this by not using the double data type at all:
formattedValue = numberFormat.format(new BigDecimal(number));
I have double var and I need to make it in 0.00 format. Works fine with this:
sum = Math.round(sum*100.00)/100.00;
I return it by
return Double.toString(sum);
But instead of for example 2.40 it gives me 2.4 (missing 0 at the end).
I have these imports available:
import static org.junit.Assert.*; import java.util.*;import org.junit.Test;
I solved the problem with DecimalFormat and BigDecimal, but i can't use those libraries.
You can simple format the String
double num = 2.402;
String output = String.format("%.2f", num);
System.out.println(output);
You can use java.lang.String#format() or java.util.Formatter to print the number in a convenient manner.
return String.format("%.2f", sum);
should do the job.
Simply use format
example:
package com.test;
import java.lang.*;
import java.util.*;
public class StringDemo {
public static void main(String[] args) {
double piVal = Math.PI;
/* returns a formatted string using the specified format
string, and arguments */
System.out.format("%f\n", piVal);
}
}
output: 3.141593
The %f allows for the amount of digits you wanna incudes ot %.2f includes 2 digits after.
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
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));
Need result with sign, except for 0.0d. Ie:
-123.45d -> "-123.45",
123.45d -> "+123.45",
0.0d -> "0".
I invoke format.setPositivePrefix("+") on the instance of DecimalFormat to force the sign in the result for positive inputs.
I'm sure there is a more elegant way, but see if this works?
import static org.junit.Assert.assertEquals;
import java.text.ChoiceFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import org.junit.Test;
public class NumberFormatTest {
#Test
public void testNumberFormat() {
NumberFormat nf = new MyNumberFormat();
assertEquals("-1234.4", nf.format(-1234.4));
assertEquals("0.0", nf.format(0));
assertEquals("+0.3", nf.format(0.3));
assertEquals("+12.0", nf.format(12));
}
}
class MyNumberFormat extends NumberFormat {
private DecimalFormat df = new DecimalFormat("0.0#");
private ChoiceFormat cf = new ChoiceFormat(new double[] { 0.0,
ChoiceFormat.nextDouble(0.0) }, new String[] { "", "+" });
#Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
return toAppendTo.append(cf.format(number)).append(df.format(number));
}
#Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
return toAppendTo.append(cf.format(number)).append(df.format(number));
}
#Override
public Number parse(String source, ParsePosition parsePosition) {
throw new UnsupportedOperationException();
}
}
According to DecimalFormat
The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern
Hence new DecimalFormat("0.0#") is equivalent to new DecimalFormat("0.0#;-0.0#")
So this would give us: -1234.5 and 1234.5
Now, to add the '+' to positve numbers, I use a ChoiceFormat
0.0 <= X < ChoiceFormat.nextDouble(0.0) will use a choice format of "". ChoiceFormat.nextDouble(0.0) is the smallest number greater than 0.0.
ChoiceFormat.nextDouble(0.0) <= X < 1 will use a choice format of "+".
If there is no match, then either the first or last index is used, depending on whether the number (X) is too low or too high. If the limit array is not in ascending order, the results of formatting will be incorrect. ChoiceFormat also accepts \u221E as equivalent to infinity(INF).
Hence
Double.NEGATIVE_INFINITY <= X < 0 will use "".
1 <= X < Double.POSITIVE_INFINITY will use "+".
Thanks a lot guys, some very good ideas here.
Based on what has been suggested, I decided to use two formats: zeroFormat for special-casing for 0.0d, and nonZeroFormat for the rest of the cases. I am hiding the implementation behind an IDisplayableValueFormatter (that is used by a custom UI control) and don't need to adhere to the NumberFormat contract/interface.
Java has both a "negative zero" and a "positive zero". They have different representations, but compare as being equal to each other.
If you must have a plus sign preceding your positive values, but you don't want it for positive zero, then you may need to do something like this to temporarily clear the prefix:
try {
if (val == 0.0) {
format.setPositivePrefix("");
}
result = format.format(val);
}
finally {
format.setPositivePrefix("+");
}
I just ran into this on a project, and I didn't find any of the answers here particularly satisfactory.
What I was able to do instead (which may or may not work for you) is:
// Convert negative zero to positive zero. Even though this
// looks like it should be a no-op, it isn't.
double correctedValue = (value == 0.0 ? 0.0 : value);
Then the value will be correctly formatted by the DecimalFormat class.
I'm actually a bit surprised that Java doesn't have a similar construct built-in.