4
$\begingroup$

Considering two situations:

I have a string "F2.5" and Quantity["2.3s"]. How can the numeric value be extracted to have:

"F2.5"` -> 2.5

Quantity["2.3s"]` -> 2.3

Thanks!

$\endgroup$
8
  • 1
    $\begingroup$ QuantityMagnitude[Quantity["2.3", "Seconds"]] $\endgroup$
    – Julian
    Commented Jun 24, 2015 at 10:52
  • $\begingroup$ Why not simply drop the first character and use ToExpression? $\endgroup$
    – Yves Klett
    Commented Jun 24, 2015 at 11:16
  • $\begingroup$ @Julian you don't know if it is Seconds or other measurement unit $\endgroup$
    – SuTron
    Commented Jun 24, 2015 at 11:32
  • 1
    $\begingroup$ List @@ Quantity["2.3s"] // First $\endgroup$
    – SquareOne
    Commented Jun 24, 2015 at 11:35
  • 1
    $\begingroup$ First@(2.3 s) yields 2.3 $\endgroup$
    – thils
    Commented Jun 24, 2015 at 11:37

3 Answers 3

6
$\begingroup$
StringDrop["F2.5", 1] // ToExpression

StringDrop["2.5F", -1] // ToExpression

and

List @@ Quantity["2.3s"] // First

or rather as @thils proposed, directly

Quantity["2.3s"] // First
$\endgroup$
5
$\begingroup$

Internal`StringToDouble seems applicable:

Internal`StringToDouble /@ {"F2.5", "2.5F"}
{2.5, 2.5}

The evaluated form of Quantity["2.3s"] is Quantity[2.3`,"Seconds"] therefore as already commented:

Quantity["2.3s"][[1]]
2.3

System`Convert`TableDump`ParseTable provides configurable options for processing strings.

$\endgroup$
3
  • $\begingroup$ Nice ! I was looking in the $ImportFormats but failed to find something useful ... $\endgroup$
    – SquareOne
    Commented Jun 24, 2015 at 12:31
  • $\begingroup$ Do you know in which functions this internal is used ? This works: ImportString["2.5F", "List"] but it does not for "F2.5" ... Interpreter["Number"]["F2.5"] or Interpreter["Number"]["2.5F"] do not work either ... $\endgroup$
    – SquareOne
    Commented Jun 24, 2015 at 12:45
  • $\begingroup$ @SquareOne I seem to recall coming across an explicit use of Internal`StringToDouble by a built-in function but I cannot recall where at the moment. If I do later I'll let you know. $\endgroup$
    – Mr.Wizard
    Commented Jun 24, 2015 at 12:53
3
$\begingroup$

This may be more robust, assuming you want to see the specific letter "F":

 ToExpression@StringCases[ #,
        {"F" ~~ s : NumberString -> s, 
         s : NumberString ~~ "F" -> s}] & /@
             {"F3.14", "2.718F","an embedded number F2.34 in a string"}

{{3.14}, {2.718}, {2.34}}

$\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.