Beginner
Beginner

Reputation: 171

Convert exponential values in a String into a decimal representation without exponential notation

I have a string build like this :

String str = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526"

There is -7.5e-4 that I would like to change into -0.00075

I would like to change the exponential value to decimal value to obtain something like this :

String str = "m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526"

I have lots of string like this to check and transform.

I don't really know how to change efficiently the exponential values, because all these values are in a string...

If you know an efficient and fast way to do that, please, tell me.

Upvotes: 0

Views: 6399

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

You can parse with Double.parseDouble then format with String.format():

    double d = Double.parseDouble("-7.5e-4");
    String s = String.format("%f", d);

Upvotes: 0

dambros
dambros

Reputation: 4392

Something like this should do the job:

public static void main(String[] args) {
    String patternStr = "[0-9.-]*e[0-9.-]*";
    String word = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(word);
    if (matcher.find()) {
        Double d = Double.valueOf(matcher.group());
        System.out.println(word.replaceAll(patternStr, BigDecimal.valueOf(d).toPlainString()));
    }

}

Output will be:

m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526

Of course if there are multiple exponentials on the String you will have to tweak it a bit.

Upvotes: 1

Maljam
Maljam

Reputation: 6274

You can use the method toPlainString in the BigDecimal class:

String num = "7.5e-4";
new BigDecimal(num).toPlainString();//output 0.00075

Upvotes: 3

Related Questions