2
$\begingroup$

I'd like to create a custom number format for use with ToString. However if I do the obvious and create a function that calls NumberForm with modified options:

numberform = 
  NumberForm[#, 
    ExponentFunction -> (If[-5 < # < 5, Null, #]&), 
    NumberFormat -> (If[#3 != "", SequenceForm[#1, "E", #3],#1]&)]&  
Slot[1]&

It works fine as a function:

numberform[1234567890.]  
1.23457E9

but not with ToString:

ToString[1234567890., numberform]  
ToString[1.23457*10^9, Slot[1]&]

Is there some attribute I have to set to make it behave like the built-in forms? Is that even possible? Is there a workaround?

$\endgroup$
2
$\begingroup$

You can use TagSet (/:). This attaches the definition to numberform instead of ToString:

ClearAll[numberform];
numberformFunction = 
  NumberForm[#, ExponentFunction -> (If[-5 < # < 5, Null, #] &), 
    NumberFormat -> (If[#3 != "", 
    SequenceForm[#1, "E", #3], #1] &)] &;
numberform /: ToString[s_, numberform] := numberformFunction@s;
ToString[1234567890., numberform]

1.23457E9

$\endgroup$
  • $\begingroup$ That's an ingenious idea that I'm happy to have been exposed to, but mostly it reminded me that there was a trick not in the documention of ToString that I once knew and had forgotten: all I had to do in the first place was ToString[numberform[1234567890.]]. Thanks. $\endgroup$ – Mark Barton Jun 17 '14 at 23:18
2
$\begingroup$

Why not simply

numberform = 
 NumberForm[ToExpression@#, 
   ExponentFunction -> (If[-5 < # < 5, Null, #] &), 
   NumberFormat -> (If[#3 != "", SequenceForm[#1, "E", #3], #1] &)] &

???

numberform[ToString@123456.]

1.23456E5

numberform[123456.]

1.23456E5

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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