# numerics – surprised Rationalize will sometimes leave a Real unchanged

``````myRationalize(x_Integer) := x;
myRationalize(x_Rational) := x;
myRationalize(0.) := 0;
myRationalize(x_Real) := Block(
{y},
y = Rationalize@x;
If(Head@y === Real, y = Round(x*1000000000.)/1000000000);
y
)
``````
``````myRationalize(571628.2812`)
(* 1429070703/2500 *)
myRationalize((1/3)*1.)
(* 1/3 *)
``````

The magic number used is one billion, which takes care of my use case of counting wholes and fractions of grams of plastic resin pellets to the (frankly unnecessary) precision used by an MRP inventory system. I would prefer a solution without using a magic number based on knowing the domain of the problem.

I was thinking about using RealDigits manipulation to calculate a number to replace the magic constant…

``````RealDigits(571628.2812`)
(* {{5, 7, 1, 6, 2, 8, 2, 8, 1, 2, 0, 0, 0, 0, 0, 0}, 6} *)
``````

…but I was unexcited to strip zeros, take due care of wherever the decimal point may be, etc. Properly careful code will be slow, I guessed.

Posted on Categories Articles