Reputation:
I have got two strings change_inpoints and change_inpercentage .
I need to round it off after two decimal points .
String change_inpoints = "510.663757";
String change_inpercentage = "+0.095152%";
This is what i tried
import java.text.DecimalFormat;
public class RounditOff {
public static void main(String[] args) {
String change_inpoints = "510.663757";
String change_inpercentage = "+0.095152%";
double d_inpoints = Double.parseDouble(change_inpoints);
DecimalFormat decimal = new DecimalFormat("#.00");
System.out.println("change in points " +decimal.format(d_inpoints));
change_inpercentage = change_inpercentage.replace("+", "");
change_inpercentage = change_inpercentage.replace("-", "");
change_inpercentage = change_inpercentage.replace("%", "");
double d2_percentchange = Double.parseDouble(change_inpercentage);
DecimalFormat decimal_2 = new DecimalFormat("#.00");
System.out.println("change in percent " +decimal_2.format(d2_percentchange));
}
}
But the issue with chnage_inpercent is that i am
For example the current output for change_in percent is .10
it should be 0.10%
Could you please tell me how to do it in better way
Upvotes: 2
Views: 57
Reputation: 44
You can use this:
DecimalFormat decimalFormat = new DecimalFormat("#.##%");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
the default rounding mode is "HALF_EVEN".
decimalFormat.format(change_inpercentage);
Upvotes: 0
Reputation: 1091
Use
new DecimalFormat("0.00");
instead of
new DecimalFormat("#.00");
as # means "Digit, zero shows as absent " For the percentage sign you could use the % prefix/suffix (0.00%).
Here you can find more information on DecimalFormat.
Upvotes: 3
Reputation: 22254
Just change the format to
DecimalFormat decimal_2 = new DecimalFormat("0.00%");
This will put a zero before the dot and append the %
char afterwards
Upvotes: 0