Message Boards Message Boards

0
|
6925 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Use NumberForm, FortranForm, CForm, and so forth in FormFunction?

Posted 8 years ago

I am having trouble with a very basic issue of formatting numbers. Here is an example:

CloudDeploy[FormFunction["x" -> "Number", FortranForm[#x] &]]

In the website, I enter a number like "1.23*^25" in the input field and hit ENTER. I expect a return of "1.23e25". In fact, the return is an image in which "x Slot" is written.

I have tried various permutations of wrappers like FortranForm, CForm, NumberForm, and so forth, and various other attempts with Delayed, none of which gives the desired result. To be clear, I don't want to get back an image (e.g., as possible with ExportForm[ ]). I would just like to get back a simple string such as "1.23e25".

[In the absence of any wrapper, the return is: ' 12300000000000000276824064'. Hence, there is a need for a wrapper.]

My question seems so simple. Any solutions?

Thank you!

POSTED BY: Scot Martin
3 Replies

This is because FortranForm, CForm et al are not properly functions, they don't evaluate. As a matter of fact they just change the out cell in the frontend. Same goes for InputForm, FullForm, TraditionalForm. Because of that they mostly just work in the frontend.

In order to achieve what you want you'd need to use ToString with two arguments:

In[49]:= ToString[1.23*^25, CForm]

Out[49]= "1.23e25"
POSTED BY: Carlo Barbieri
Posted 8 years ago

Fantastic answer, Carlo. Just what I needed. Grazie!

POSTED BY: Scot Martin
Posted 8 years ago

By the way, here is a non-elegant workaround. This solution essentially duplicates the work of NumberForm. After looking at some of the codes generated by CloudDeploy, I see that the 'processor' strips out all formatting wrappers, no matter how hard I try to keep them in. :-) So here is a workaround below. I'd be interested in someone else's more elegant solution.

formatFunction[value : _] :=

 Module[
  {mantissaExponent, mantissa, exponent, numericalValue = N[value]},

  CompoundExpression[
   mantissaExponent = MantissaExponent[numericalValue],
   mantissa = 10 First@mantissaExponent,
   exponent = Last@mantissaExponent - 1,
   Which[
    (*if*)
    -4 <= exponent <= 4,
    ToString@numericalValue,
    (*else*)
    True,
    ToString[Row[{mantissa, " \[Times] 10^", exponent}]]
    ]
   ]
  ]

Followed by deploying:

CloudDeploy[FormFunction["x" -> "Number", formatFunction[#x] &]]

An additional nice format that uses superscripts instead of "E" notation can be obtained within many FormPage[ ] results by using the HTML mixed expression below in place of the corresponding line in the function above:

ToString[Row[{mantissa, " \[Times] 10<sup>", exponent, "</sup>"}]]
POSTED BY: Scot Martin
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract