# Output formatting

Is it possible to format a mathematica output in a way that all the fractional numbers are written first followed by other constants or functions?

Example:

output= 12/7*x + 120/17*x*y

or

output= (12*x)/7 + 120/17*x*y

which when saved in a file becomes

(12*x)/7 + (120*x*y)/17

However I was asking if the output can be formatted in the following form

12/7*x + 120/17*x*y

PS. I am wring the expression as a .m extension and running this file through a terminal. I am not using notebook .nb interface.

• Is this helpful?: mathematica.stackexchange.com/questions/98121/… Aug 22, 2019 at 3:54
• @theorist , this link is useful. However the solutions there does not work if one uses .m file and run through terminal. The reason of such requirement is two-fold. One is the expression will look clean if the numbers are separated from the variables. Two, it will be useful for further processing in other languages like Bash, latex etc. But it seems this does not work for .m Aug 22, 2019 at 20:06

Sounds like you want to control the OutputForm of an expression. In that case, you could do something like:

Unprotect[Times];
Format[r_Rational t_, OutputForm] := SequenceForm[r] SequenceForm[t]
Protect[Times];

For example:

12/7*x + 120/17*x*y //OutputForm
12     120
-- x + --- x y
7      17

Update

From the comments, it seems you want to control the formatting when using Put. Since Put uses InputForm when writing to a file, you need to modify InputForm instead. So:

Unprotect[Times];
Format[r_Rational t_, InputForm] := SequenceForm[r] SequenceForm[t]
Protect[Times];

Example:

(12/7*x + 120/17*x*y) >> output.dat;
Import["output.dat", "String"]

"12/7*x + 120/17*x*y "

• Wow! this works!! many thanks. Aug 22, 2019 at 20:32
• But there is one problem. It does not write as 12/7*x + 120/17*x*y rather on multiple lines. One purpose is to of course beautification but other purpose is to further process the output to Bash or latex. Aug 22, 2019 at 20:35
• Basically whatever be the expression, the output should write the numerical numbers first then any variables. This will be useful for further processing in bash or latex etc. Aug 22, 2019 at 20:42
• @Boogeyman What does 12/7 look like in your terminal? That is, does your terminal use OutputForm or something else (InputForm)? Aug 22, 2019 at 20:55
• On terminal 12/7 is written as OutputForm i.e. the way it is written in your answer. However when I save it 12/7*x (or 12*x/7) >> output.dat, it saves as (12*x)/7 but I need it to save as 12/7*x i.e. any numerical values printed first followed by any variables. Aug 22, 2019 at 21:00

Does something like this give you what you want?