3
$\begingroup$

My current code is:

round = .1;
f[x_] := x + 4 - Sqrt[3 x^2 - 5]
xx = Solve[f[x] == 0, Reals];
StringForm["x=`1`", 
If[Length[xx] >= 1, Round[Max[xx[[All, 1, 2]]], round], 
"none"]]

x=5.800000000000001`

which i want to give me an output of "x = 5.8" instead.

Any advice would be appreciated.

$\endgroup$
2
  • $\begingroup$ StringForm["x=1", If[Length[xx] >= 1, Round[Max[xx[[All, 1, 2]]], round // Rationalize] // N, "none"]] $\endgroup$
    – Bob Hanlon
    Mar 7, 2019 at 23:41
  • 1
    $\begingroup$ Could round exactly and then use N: N[Round[Max[xx[[All, 1, 2]]], 1/10]] $\endgroup$ Mar 7, 2019 at 23:42

3 Answers 3

5
$\begingroup$

You could add a StandardForm wrapper:

StringForm["x=`1`",StandardForm @ If[Length[xx]>=1,Round[Max[xx[[All,1,2]]],round],"none"]]

x=5.8

$\endgroup$
1
  • $\begingroup$ Thank you! that worked and i have no idea why, i'll read the documentation for standardForm $\endgroup$
    – Wombles
    Mar 7, 2019 at 23:40
4
$\begingroup$
StringForm["x=`1`", If[Length[xx] >= 1, 
  DecimalForm[Round[Max[xx[[All, 1, 2]]], round], DefaultPrintPrecision -> 2], 
  "none"]]

x = 5.8

Same result with NumberForm in place of DecimalForm.

$\endgroup$
1
  • $\begingroup$ Thank you, this worked great $\endgroup$
    – Wombles
    Mar 8, 2019 at 1:23
2
$\begingroup$
StringJoin["x=",If[Length[xx] >= 1, ToString[Round[Max[xx[[All, 1, 2]]]*10]/10.]]]

x = 5.8

Round[q*10] rounds 10q to the nearest integeger.

Round[q*10]/10 rounds q to the nearest tenth.

ToString turns an expression into a string and StringJoin joins strings, both aptly named ...

$\endgroup$
1
  • $\begingroup$ Just fixed a typo (was missing a right bracket (])). $\endgroup$
    – mjw
    Mar 8, 2019 at 3:59

Your Answer

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

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