4
$\begingroup$

Given this (simplified and much shorter than the real case) string:

s="The value is now 3.219209e3, it has grown by 1.06e01 in the last year"

I would like to change the format of the numbers from the "e" notation to plain numbers:

"The value is now 3219.209, it has grown by 10.6 in the last year"

I have tried variations with StringReplace to do this e.g.:

StringReplace[s, StringExpression[m : NumberString, "e", e : NumberString] :>(ToExpression[m]*10^ToExpression[e])]

Which returns a StringExpression instead of a String:

"The value is now " ~~ 3219.21 ~~ ", it has grown by " ~~ 10.6 ~~ " in the last year"

Clearly I'm doing something wrong, is there a way of changing the format of numbers in a string like this that returns a String instead of a StringExpression?

$\endgroup$

2 Answers 2

5
$\begingroup$

You can use ToString to convert the numbers into their string representation, which can then be merged properly with the rest of the string:

s =  "The value is now 3.219209e3, it has grown by 1.06e01 in the last year";

StringReplace[s,
 m : NumberString ~~ "e" ~~ e : NumberString :>
  ToString[ToExpression[m]*10^ToExpression[e]]
 ]
(* "The value is now 3219.21, it has grown by 10.6 in the last year" *)
$\endgroup$
1
  • $\begingroup$ Thanks @Lukas, a neat solution $\endgroup$
    – EstabanW
    Oct 23, 2022 at 10:23
3
$\begingroup$

Using the functionality provided by RegularExpression along with Interpreter:

s = "The value is now 3.219209e3, it has grown by 1.06e01 in the last year"

nums = StringCases[s, 
  RegularExpression["[-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?"]
  ]

{"3.219209e3", "1.06e01"}

rule = Thread[Rule[nums, ToString@Interpreter["Number"][#] & /@ nums]]

{"3.219209e3" -> "3219.21", "1.06e01" -> "10.6"}

StringReplace[s, rule]

This above can be written succinctly as:

StringReplace[s, 
 k : RegularExpression["[-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?"]
  :> ToString@Interpreter["Number"][k]]

Result:

"The value is now 3219.21, it has grown by 10.6 in the last year"

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.