Print double with variable precision (not rounded) in Java [duplicate] - java

This question already has answers here:
Format Float to n decimal places
(11 answers)
Closed 7 years ago.
I am looking to print a double to a variable precision, but without rounding. For example:
Scanner input = new Scanner(System.in);
double num;
System.out.println("Enter a double:");
num = input.nextDouble();
int precision;
System.out.println("Enter precision:");
precision = input.nextInt();
Now I want to print num to the decimal place of precision. Is there a simple way to print this?
EDIT:
I have not seen another question answered as to how to use a variable value. The DecimalFormat option rounds the number, which I do not want. Ideally, I am looking for a way to use a variable in:
"%.nf"
rather than
"%.3f"

Use, as a formatted String, "%.nf", where n is replaced by the number of decimal places.
Example:
System.out.printf("%.1f, %.2f\n", 1.234d, 1.234d);
// 1.2, 1.23
See the Javadoc.
To insert a variable into this, just do "%." + intValue + "f".

Related

Take the decimal part of a double/float number [duplicate]

This question already has answers here:
How do I get whole and fractional parts from double in JSP/Java?
(18 answers)
Closed 4 years ago.
I have a simple question, I want to know how can I get the decimal part from a double/float number without the dot.
Example: a=0.75 and b=3231.0131
So I would like to set those decimal values in two new Integer variables: m=75 and b=0131.
I'm going to clarify some things, I want to create a new int variable, that variable will storage the decimal part from the original number.
double a = 0.75
double b = 12.033
int x = decimalofa
int y = decimalofb
System.out.println("the decimal of"+a+"is"+x+"and the decimal of"+b+"is"+y)
//the decimal of 0.75 is 75 and the decimal of 12.033 is 033
The thing is that i'm not sure if 033 could be considered as an integer number, so in other words I just want to take all the numbers next to the point and save them in a new variable.
Just do
float a = 0.75f;
System.out.println(Float.toString(a).split("[.]")[1]);
This only works if there is a decimal and there are numbers after that decimal

How to convert int to decimal fraction? - Java [duplicate]

This question already has answers here:
percentage of two int?
(4 answers)
Closed 5 years ago.
I have such code:
int number1 = 20;
int number2 = number1/100;
I want to get percentage of number1 as 0,2 -> I suppose int should be converted into some other type. But I need 0,2 to use for BigDecimal number. How can I get this 0,2 from int number1 = 20?
int number1 = 20 has to be in that type.
Will be grateful for help.
Using a BigDecimal is appropriate here. You can use BigDecimal.valueOf in order to convert int to BigDecimal. Then, you can divide by specifying a scale and a rounding mode.
Example :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 1, RoundingMode.HALF_UP)
);
Will display :
0.2
With a different scale :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
);
It will display :
0.20
Or like stated in the question comments, you can also create directly the BigDecimal from a String :
System.out.println(new BigDecimal("0.2"));
Divide the int by a floatvalue to give to it a floating number representation and assign it to a floating number.
float number2 = number1/100F;

How to modify Double value in android [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Double decimal formatting in Java
(14 answers)
Closed 6 years ago.
Suppose, I have a double value.
double dble = 5.91742691
Now can I get that value with two digits after the point. I mean to say,can I get 5.91 from there programmatically?
One more, suppose, I want to get an integer from a double value if the double value is X.9XXXXX. Here I mean to say, I want to compare the AFTER-POINT value. For your understanding here dble's AFTER-POINT value is 91742691. How can I do that?
If you want to truncate a double to 2 decimal places, do
double twoDecDbl = (int)(dble * 100) / 100.0; // 5.91
or
double twoDecDbl = Math.floor(dble * 100) / 100; // 5.91
However, if you want to get the numbers after the decimal place as an integer (which I don't know why you would want to do this), then do
long decimals = Long.parseLong(("" + dble).split("\\.")[1]); // 91742691
Note: The maximum value of an int is 2,147,483,647 (10 digits there), but a double can hold 16 digits after the decimal point, so a long must be used in order to stay safe (can have 19 digits). Alternatively, you can just keep it as a String by removing the wrapping parse.
For #1 Try it
NumberFormat formatter = new DecimalFormat("#0.00");
String s = formatter.format(dble);
double num = Double.valueOf(s);
or
dble = Math.floor(dble * 100) / 100;
For #2 Try it
double num = dble - (int)dble;
In case Integer.MIN_VALUE < dble < Integer.MAX_VALUE

Format double to 2 decimal places [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I am trying to Format my double value to exact 2 decimal places and it seems to working fine, here is the code i am trying
final NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
df.format(value)
Till now everything is working, but i need to return double value as it is being used for other calculations and i tried
Double.parseDouble(df.format(value))
with big decimal like
BigDecimal price = new BigDecimal(df.format(number));
but it is not working as expected
like 18.50 is being converted as 18.5
Though this is not an issue with calculations but i need to show amount on the UI where i have to show exactly up to 2 decimal places.
Is there any was i can handle it in java class or i have to take care in JSP with JSTL
This is what BigDecimal is made for!
BigDecimal number = new BigDecimal(123.456);
// set 2 fraction digits
// Note that setScale() does not change the original,
// but returns a new BigDecimal.
number = number.setScale(2, RoundingMode.DOWN);
// get string representation
String text = number.toPlainString();
// get double value
double dbl = number.doubleValue();
And use BigDecimal for other calculations as well if you can.

How to truncate the double value? [duplicate]

This question already has answers here:
Are there any functions for truncating a double in java?
(11 answers)
Closed 9 years ago.
I want to truncate the double.
e.g.
double d=3.123456789087654;
if I want to truncate It to the 10th digit after the decimal
the result should be
result: 3.1234567890
I don't need round off value as a result
I tried my own function as
static double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
but didn't get the appropriate result as I want..
can anybody please help me to clear my problem.
Does java supports such any function that supports truncation not round off??
In general, you can't, at least not by using double. The reason is that many numbers simply can't be represented exactly, even if they have a small number of decimal digits.
Take 0.1 as an example. The nearest double is 0.1000000000000000055511151... and no amount of truncation would give you exactly 0.1.
You can use the DecimalFormat class.
double d = 3.123456789087654;
DecimalFormat newFormat = new DecimalFormat("#.##########");
double tenDecimal = Double.valueOf(newFormat.format(d));
this will round the last digit.
I am agree with NPE. no amount of truncation would give you exactly 0.1.
only way is to convert in to string and after substring convert back to double.

Categories

Resources