1

I would like to show the cents of the dollar amount as superscripts inside text.

I can define a function for making the cents into a superscript, but when I add the result in text, the text gets placed in the superscript line.

The formatting functions are:

dollarSuperscriptCents[x_?NumericQ] := ToString[Floor[x]]^
 If[x - Floor[x] > 0, ToString@droptrailingperiod[100 (x - Floor[x])],
   ""]
droptrailingperiod[x_] := 
 If[Round[x] == x,(*is the rightmost a period, from some precision?*)
  Round[x](*then use Round to drop the trailing period*)
  , x]

But if I then use Style["I owe $"<>ToString@dollarSuperscriptCents[3.75]<>".", FontFamily -> "Georgia"] then the result is

I owe $75

3.

I tried to look into Box commands but this quickly got too complex. Many thanks.

Nicholas G
  • 1,981
  • 10
  • 15

1 Answers1

4
Clear["Global`*"]

EDIT: Corrected to handle cent values less than 10

dollarSuperscriptCents[x_?NumericQ] :=
 Module[{xv = Round[x, 1/100], cents}, 
  cents = 100*FractionalPart[xv];
  Superscript[ToString[Floor[xv]], If[cents == 0, "", 
   If[cents < 10, "0", ""] <> ToString[cents]]]]

Column[Style[StringForm["I owe $``.", dollarSuperscriptCents[#]], FontFamily -> "Georgia"] & /@ {2.999, 3, 3.0, 3.05, 3.75, 3.756}]

enter image description here

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
  • Many thanks. How does one concatenate StringForms? StringJoin does not work! – Nicholas G Apr 09 '22 at 16:13
  • 1
    Use Row, e.g., Row[Riffle[Style[StringForm["I owe $``.", dollarSuperscriptCents[#]], FontFamily -> "Georgia"] & /@ {2.999, 3, 3.0, 3.75, 3.756}, " "]] – Bob Hanlon Apr 09 '22 at 16:24
  • I was wondering whether StringForm would resolve the inability of text3D to render subscripts and other boxed expressions, but I could not make it work. If you could, that would be great. See https://mathematica.stackexchange.com/questions/131798/placing-text-in-3d-not-facing-viewer/131842 – Nicholas G Apr 27 '22 at 08:21