1
$\begingroup$

I would like the output of ToString to keep the zeros as in the input, how can I do that?

In[145]:= ToString[2.00, InputForm]

Out[145]= "2."  

update

problem solved as follows

In[249]:= ToString[NumberForm[2., {1, 2}]]

Out[249]= "2.00"  

Or, as suggested by @Shin Kim

In[257]:= ToString[-2`3]

Out[257]= "-2.00"

Now, I would like also to keep the sign - or + if possible, it works with - but with + not

In[250]:= ToString[NumberForm[+2., {1, 2}]]

Out[250]= "2.00"
$\endgroup$
4
  • $\begingroup$ The problem is that Mathematica front end immediately simplifies/rewrites 2.00 to 2. before even the kernel gets hold of it. If you write 2.00 it becomes 2. Even HoldForm[2.00] does not prevent this. $\endgroup$
    – Nasser
    Commented Feb 15, 2022 at 8:50
  • 2
    $\begingroup$ You can, however, play with NumberForm to include a specified number of zeros, if that helps. $\endgroup$
    – thorimur
    Commented Feb 15, 2022 at 8:58
  • $\begingroup$ @thorimur, yep, that works..Thanks, man! ToString[NumberForm[2.00, {1, 2}]] $\endgroup$
    – MMA13
    Commented Feb 15, 2022 at 9:02
  • 1
    $\begingroup$ You can just do ToString[NumberForm[2.,{1,2}]] as 2.00 are the same as 2.0 which is the same as 2. saves you typing all those extra zeros. $\endgroup$
    – Nasser
    Commented Feb 15, 2022 at 9:32

1 Answer 1

2
$\begingroup$

Any number you input that has the dot . is interpreted as a floating number with the machine precision, unless your input has more digits under the decimal point than the machine precision or you specified the precision. Otherwise zeroes at the end won't really have any effect on the precision.

You can specify the precision of your numeric input via SetPrecision or simply by putting ` at the end:

In[1]:= 2`3 (*also 2.00`3*)

Out[2]= 2.00

To turn this into a string with the sign symbol,

a = 2`3;
ToString[Sign[a] /. {1 -> "+", -1 -> ""}] <> ToString[a]

(*"+2.00"*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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