I want to write a function to force Mathematica to show a rational number in a denominator I specified. For example, the rational 2/3 with the specified denominator 6 should become 4/6.
I tried using HoldForm[]
or Unevaluated[]
, but with no success.
In[1]:= setDenominator[x_, d_] := Unevaluated[Rational[x*d, d]];
In[2]:= setDenominator[2/3, 6]
2
Out[2]= -
3
You can use a FractionBox with DisplayForm:
setDenominator[x_, d_] := DisplayForm[FractionBox[x*d, d]]
HoldForm
works but you have to be sneaky to get the numerical value of x*d
in there
setDenominator[x_, d_] := HoldForm@Rational[foo, d] /. foo -> x*d
This can be improved by adding some checks for the suitability of d
.
Here's a variation on sakra's idea that allows for addition and multiplication...
Format[setDenominator[x_, d_]] := DisplayForm@FractionBox[x*d, d]
setDenominator /: Plus[left___, setDenominator[x1_, d1_], right___] := left + x1 + right;
setDenominator /: Times[left___, setDenominator[x1_, d1_], right___] :=left*x1*right;
Trying it out:
a = setDenominator[3/5, 10];
Print[a, " + ", 2/3, " = " , a + 2/3]
Print[a, " + ", 2/3, " = " , setDenominator[a + 2/3, 30]]
Print[a, " × ", 2/3, " = " , a * 2/3]
Print[a, " × ", 2/3, " = " , setDenominator[a * 2/3, 30]]
Print[a, " ÷ ", 2/3, " = " , a /( 2/3)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With