Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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

share|improve this answer
    
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. –  Mark Barton Jun 17 at 23:18

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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