user663724
user663724

Reputation:

How to round it off string number after two decimal points which contains special characters?

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

  1. loosing number before the decimal point
  2. how can i add percentage symbol at the end ??

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

Answers (3)

Dustin
Dustin

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

mad_manny
mad_manny

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

Manos Nikolaidis
Manos Nikolaidis

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

Related Questions