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.
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'm trying to make a double to be this format 00,00
Example
9,21341 > 09,21
10,4312 > 10,43
1,01233 > 01,01
42,543 > 42,54
Currently I'm using the String.Format to round the double
String.format("%s %02.2f - ", example.getName(), example.getDouble());
This does not add the extra zero in front of the double if it is smaller than 10.
Formatter class (which is the basis of String.format method) operates using the concept of "fields". That is, each field is of some specific size and can be padded. In your case, you could use a formating like %05.2f, which would mean a field of size 5, with 2 symbols after the point padded with zeroes to the left.
However, if you need some fine-grained formatting of numbers usually what you are looking for is DecimalFormat class, which allows you to easily customize how the numbers are represented.
Example (ideone link):
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
DecimalFormat decimalFormat = new DecimalFormat("#00.00");
System.out.println(decimalFormat.format(0.99f));
System.out.println(decimalFormat.format(9.99f));
System.out.println(decimalFormat.format(19.99f));
System.out.println(decimalFormat.format(119.99f));
}
}
Output:
00.99
09.99
19.99
119.99
I tried to get the local decimal separator with the following code:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
//option 1
DecimalFormat format=(DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
public char sep=symbols.getDecimalSeparator();
//option 2
double value = 1234.5;
NumberFormat fmt = NumberFormat.getInstance();
String formatted = fmt.format(value);
public String decSep= formatted.substring(5,6);
//option 3
public Locale loc=Locale.getDefault();
DecimalFormatSymbols symbols= new DecimalFormatSymbols(loc);
public char sep=symbols.getDecimalSeparator();
public String decSep=Character.toString(sep);
but I always get "," even if the setting is set to "."
I tried with VB.NET code and it works.
What's wrong or missing in Java code ?
I appreciate your help
Try this :
Locale.setDefault(Locale.US);
This will set every output number with decimal separator. You can also take some input numbers with decimal separator.
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
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.