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.
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
My problem while I am converting Double to BigDecimal I am loosing original value.
My requirement like input would be like Double val = 10435383974769502920d and want to convert like 10435.383974769502920 but getting below output.
I have tried with Double BigDecimal..but no success
Double val = 10435383974769502920d;
System.out.println(BigDecimal.valueOf(val).movePointLeft(15));
output : 10435.383974769502
Double val = 10435383974769502920d;
A double simply can't hold that many digits. Doubles are limited to ~15 decimal digits of precision. It's not BigDecimal that's losing the extra digits; it's the double you're starting with.
>>> System.out.printf("%f\n", 10435383974769502920d);
10435383974769502000.000000
Construct the BigDecimal with a string to avoid losing precision.
String val = "10435383974769502920";
System.out.println(new BigDecimal(val).movePointLeft(15));
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
What's the best practice to round a float to 2 decimals? [duplicate]
(7 answers)
Closed 9 years ago.
I've got a float value and i need to have only two decimals after comma. I'm using this code:
public static float getWhatINeed() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
float total =
((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
return total;
}
And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:
String s = String.format("%.2f", 1.2975118);
somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?
There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.
If you really NEED 2 decimals, use BigDecimal
You basically have 4 options:
return a float and deal with the fact that there are n decimal places
format to a String (which means a lot of string parsing if you need to do calculation)
convert to use BigDecimal
convert to use int and assume that the ones digit represents hundredths.
Did you try:
new DecimalFormat("00.00").format(1.2975118);
You can try as follows
DecimalFormat df = new DecimalFormat("0.##");
float a=1.256f;
System.out.println(df.format(a));
}
Out put
1.26
After setting precision and get as a String You can canvert it back to float by
float f = Float.parseFloat(YourString);
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have the following and the question is, for example if zzi = 95 then myNum will be correctly displayed as 32.33, exactly as I want it too with two decimal places.
However if zzi = 94, myNum will be displayed as 32.0 instead of 32.00
How to display it as 32.00?
float xFunction(int zzi) {
float myNum = (zzi + 2);
myNum = myNum / 3;
int precision = 100; // keep 4 digits
myNum = (float) (Math.floor(myNum * precision + .5) / precision);
return myNum;
}
Thanks before.
Your question is not so much about rounding a number as it is about rounding a display or String representation of a number. The solution:
Use new DecimalFormat("0.00");
Or String.format("%.2f", myNumber);
Or new java.util.Formatter("%.2f", myNumber);
Or System.out.printf("%.2f", myNumber);
Note: avoid use of float whenever possible, and instead prefer use of double which greatly improves numeric precision at little cost. For financial calculations use neither but instead opt for integer calculations or use BigDecimal.
Remember:
1) printing the number displaying two decimal places is very different from rounding the actual value. In other words "representation" != actual value.
2) floating point values are always imprecise. Even with rounding, you may or may not get an "exact value".
Having said that, the simplest approach is:
float myNum = ((123.456 * 100.0) + .5) / 100.0;
new DecimalFormat("#.##").format(myNum );
You can use DecimalFormat
System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
You should work on the printing function. I assume you are using a System.out.println: replace it with
System.out.format("%.2f", numberToPrint);
Read the docs for that function to discover more about format strings.
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.
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));