As the title says, I want to limit the number of decimals that result from an operation with variables of type double, this result is displayed in a JTextArea of a JFrame.
The code that does the operation and prints the result in the JTextArea is as follows: ( la
, lb
and lc
represent the sides of a triangle, a
calculates the area and A
is the JTextArea where the result is printed).
if (lb+lc>la && la+lc>lb && la+lb>lc){
a=Math.sqrt((la+lb+lc)*(-la+lb+lc)*(la-lb+lc)*(la+lb-lc)/16);
p=la+lb+lc;
A.setText("El triangulo es "+t+".\nEl area es ("+a+").\nEl perimetro es ("+p+").");
There are many ways to limit the number of output decimal places (Presentation) of a
double
, but not the number itself, for example todouble number = 1.4159999999;
limit the output to 2 decimal places. if you want more digits it's a matter of adding zeros to String.formatdecimalformat
and printf setScale BigDecimal`Round, cambiar el 2 por por la cantidad deseada en
y
Y y en
de
Using DecimalFormat
Using String.Format
If you just want the output to have that format you would apply numberformat
Using Math.Round() where the number of zeros is the number of decimal places to limit
Using the BigDecimal class , using the setScale method that receives two parameters: the number of decimal places to limit and the rounding mode
Try using String.format
You can combine everything like this, in this case it is a compact form that allows you to format everything together in a single line.
Note that format automatically takes the locale setting, so depending on the country, you can use
.
or,
as a decimal separator.You can use a
DecimalFormat
. For example:It will return your value to three decimal places. You would have to add (or remove) as many zeros as decimals you want after the whole number.
The best I've found to reduce the number of decimal places in a double:
number: the value with all decimals
numberDecimals: how many decimals I want to retrieve
Eg: 2.8049999999999997 returns 2.805
double val = formatDecimals( 2.8049999999999997, 3);
If you want to limit the number of unrounded decimals, you can do it like this: