So I want to use the Decimal Format class to round numbers:
double value = 10.555;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println(fmt.format(value));
Here, the variable value would be rounded to 2 decimal places, because there are two #s. However, I want to round value to an unknown amount of decimal places, indicated by a separate integer called numPlaces. Is there a way I could accomplish this by using the Decimal Formatter?
e.g. If numPlaces = 3 and value = 10.555, value needs to be rounded to 3 decimal places
Create a method to generate a certain number of # to a string, like so:
public static String generateNumberSigns(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += "#";
}
return s;
}
And then use that method to generate a string to pass to the DecimalFormat class:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = generateNumberSigns(numPlaces);
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
OR simply do it all at once without a method:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = "";
for (int i = 0; i < numPlaces; i++) {
numberSigns += "#";
}
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
If you don't need the DecimalFormat for any other purpose, a simpler solution is to use String.format or PrintStream.format and generate the format string in a similar manner to Mike Yaworski's solution.
int precision = 4; // example
String formatString = "%." + precision + "f";
double value = 7.45834975; // example
System.out.format(formatString, value); // output = 7.4583
How about this?
double value = 10.5555123412341;
int numPlaces = 5;
String format = "0.";
for (int i = 0; i < numPlaces; i++){
format+="#";
}
DecimalFormat fmt = new DecimalFormat(format);
System.out.println(fmt.format(value));
If you're not absolutely bound to use DecimalFormat, you could use BigDecimal.round() for this in conjunction with MathContext of the precision that you want, then just BigDecimal.toString().
Related
I want to get the first 2 decimal digits (without rounding ).
Here is an example:
49455.10937 --> 49455.10
formatting to String is an expensive operation (in performance terms)
this can be done with math operations:
double x = 49455.10937;
x *= 100; // moves two digits from right to left of dec point
x = Math.floor(x); // removes all reminaing dec digits
x /= 100; // moves two digits from left to right of dec point
double decimalValue = 49455.10937;
String decimalValueStr = String.valueOf(decimalValue);
int indexDot = decimalValueStr.lastIndexOf('.');
int desiredDigits=3;
String decimal = decimalValueStr.substring(0, (indexDot + 1) + desiredDigits);
decimalValue = Double.parseDouble(decimal);
System.out.println(decimalValue);
//49455.109 is console output (change desired digits)
You can use a formatter to format the double value as follows
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
Double value = 49455.10937;
System.out.println(formatter.format("The value: %.2f", value));
In java: I have some number and a number of desired decimal places in a variable (e.g. choosen by user),
and I need to print it.
myNumber = 3.987654;
numberOfDecimalPlaces = 4;
I dont want to do it like
System.out.printf( "%.4f", myNumber);
but I need to use VARIABLE numberOfDecimalPlaces instead.
Thanks a lot
Just create the format string using numberOfDecimalPlaces:
System.out.printf( "%." + numberOfDecimalPlaces + 'f', myNumber);
Can't understand why #wero is not a good answer but if you don't like to use System.out. maybe this..
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numberOfDecimalPlaces);
nf.setMinimumFractionDigits(numberOfDecimalPlaces);
String toPrint = nf.format(myNumber);
You can try with this method :
//value is your input number and places for required decimal places
public static double function(double value, int places) {
if (places < 0) {
throw new IllegalArgumentException();
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
How to get the value which is after the point.
Example:
If 5.4 is the value and I want to get the value 4 not 0.4, how can I do this?
You can use String functions for that :
public static void main(String args[]){
Double d = 5.14;
String afterD = String.valueOf(d);
afterD =afterD.substring(afterD.indexOf(".") + 1);
System.out.println(afterD);
}
first of all convert number to String,
Then using Substring get indexof(".") + 1 then print it.
& see it ll work.
OR You can try :
double d = 4.24;
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
will print : 24
suppose your input is 4.241 then you have to add 1 extra 0 in BigDecimal bd formula i.e. instead of 100 it ll be 1000.
Code:
double i = 5.4;
String[] s = Double.toString(i).split("\\.");
System.out.println(s[1]);
output:
4
Explantion:
you can convert the double to String type and after that use split function which split the converted double to String in two pieces because of using \\. delimiter. At the end, type out the second portion that you want.
you can try this
code:
double i = 4.4;
String s = Double.toString(i);
boolean seenFloatingPoint = false;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j)== '.' && !seenFloatingPoint){
seenFloatingPoint = true;
} else if (seenFloatingPoint)
System.out.print(s.charAt(j));
}
System.out.println("");
output:
4
the one line answer is
int floatingpoint(float floating){
return Integer.valueOf((Float.toString(floating).split(".")[1]));
}
which will do as follows:
convert the number e.g 56.45 to string
then split the string in string array where [0]="56" and [1]="45"
then it will convert the the second string into integer.
Thanks.
Try this way
Double d = 5.14;
String afterD = String.valueOf(d);
String fractionPart = afterD.split("\\.")[1];
Try this way
double d = 5.24;
int i = Integer.parseInt(Double.toString(d).split("\\.")[1]);
int i=(int)yourvalue;
float/double afterDecimal= yourvalue - i;
int finalValue = afterDecimal * precision;//define precision as power of 10
EX. yourvalue = 2.345;
int i=(int)yourvalue;//i=2
float/double afterDecimal= yourvalue - i;//afterDecimal=0.345
int finalValue = afterDecimal * precision;
//finalValue=0.345*10 or
//finalValue=0.345*100 or
// finalValue=0.345*1000
...
System.out.println((int)(5.4%((int)5.4)*10));
Basically 5.4 mod 5 gets you .4 * 10 gets you 4.
I am trying to create the number 0.00000.... with as many '0' as the user input wants. What is wrong with my code below?
int n;
double dec = 0.0;
in = new Scanner(System.in);
n = in.nextInt();
for (i = 1; i <= n; i++)
dec = dec / 10.0d;
Number doesn't change.
You're expecting double to retain the number of decimal digits - it doesn't do that. The value is always normalized. The double type is all about the magnitude of a number, not a particular decimal representation. It's suitable for naturally occurring quantities - weights, heights etc.
If you care about decimal digits, then BigDecimal is a more suitable type for you. This is more appropriate for currency values for example, where there really is a precise amount specified as a decimal representation.
BigDecimal does retain the number of decimal digits you use, but you'll need to be careful about exactly how you use it. You'll no doubt find the setScale method useful.
For example:
import java.math.BigDecimal;
class Test {
public static void main(String[] args) throws Exception {
BigDecimal x = new BigDecimal("0")
System.out.println(x); // 0
x = x.setScale(5);
System.out.println(x); // 0.00000
}
}
If you just want to display the decimal point according to user input, Try
int n;
double dec = 0.0;
in = new Scanner(System.in);
n = in.nextInt(); //number of decimal places
System.out.println(String.format("%."+n+"f",dec));
0.0, 0.00, 0.0000000000000000000000000000000000000000000000 and so on are exactly the same value; Java literally can't tell them apart during runtime. No matter how many times you divide it by 10, it will remain EXACTLY the same number.
When being printed, trailing zero digits are omitted (unless explicitly specified in, for instance, String.format).
Basically, what you are trying to do is keep on dividing 0.0. But it'll always give you the same result as Java considers 0.000 as 0.0. Even 0.0000000000000000 will be considered as 0.0. If you just want to display that many 0s, then save it in a String and then display.
...
StringBuilder s = new StringBuilder("0.");
for(int i = 1; i < n; i++)
s.append("0");
String num = s.toString();
//Then use it.
If you need string with user defined '0':
public static String FormatZero( int accurancy_ ) throws IllegalArgumentException
{
if( 0 >= accurancy_ )
{
throw new IllegalArgumentException( "accurancy_must be > 0" );
}
String formatString = "0.";
for( int i = 0 ; i < accurancy_ ; ++i )
{
formatString += "0";
}
DecimalFormat format = new DecimalFormat( formatString );
String result = format.format( 0d );
return result;
}
How to number formating with Java in various scenarios:
if the value is 0,then output will be zero.
if the value 1,then output will be 1.
if the value is 1.2,then output will be 1.20.
if the value is 1.20,then output will be 1.20.
So it means if the input value has decimals then i have to apply numberformat to two decimal places otherwise not required.
One DecimalFormatter isn't going to work for the case of no decimal and the case of two decimal places.
Here's some code that meets all 4 of your conditions:
DecimalFormat formatter1 = new DecimalFormat("0");
DecimalFormat formatter2 = new DecimalFormat("0.00");
double[] input = {0, 1, 1.2, 1.265};
for (int i = 0; i < input.length; i++) {
double test = Math.round(input[i]);
if (Math.abs(test - input[i]) < 1E-6) {
System.out.println(formatter1.format(input[i]));
} else {
System.out.println(formatter2.format(input[i]));
}
}
Edited to add: For jambjo, a version that manipulates the String after the DecimalFormatter.
DecimalFormat formatter2 = new DecimalFormat("0.00");
double[] input = {0, 1, 1.2, 1.265};
for (int i = 0; i < input.length; i++) {
String result = formatter2.format(input[i]);
int pos = result.indexOf(".00");
if (pos >= 0) {
result = result.substring(0, pos);
}
System.out.println(result);
}
See http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html . An example of such format would be:
double input = 1.2;
DecimalFormat formatter = new DecimalFormat("0.00");
String result = formatter.format(input);
Decimal symbol (as well as other symbols used in the result string) will be dependent on system locale (unless set otherwise) - see http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#setDecimalFormatSymbols%28java.text.DecimalFormatSymbols