2
$\begingroup$

I am trying to create a way to convert some values of numbers into currency (dollars). The example I display below takes in three random numbers between -4 and 4, and rounds them to the second decimal place. How could I create the output in $$ though? Should I try something rule based?

Clear[sequence];
sequence = RandomReal[{-4, 4}, 3];
Map[(N[Round[10^2 *#]/(10^2)]) &, sequence]

{-3.73, 2.03, 0.31}

But I want -$3.73 and so on...

$\endgroup$
4
$\begingroup$
cash = N[Round[10^2*#]/(10^2)] & /@ RandomReal[{-4, 4}, 3]

{-3.21, 2.64, -2.6}

If[Sign[#] > 0, "$" <> ToString[#], 
   "-$" <> ToString[Abs[#]]] & /@ cash

{"-\$3.21", "\$2.64", "-\$2.6"}

Note the output is a list of strings.


Or

q = Quantity[cash, "USDollars"]

{\$-3.21, \$2.64, \$-2.6}

The output is a list of Quantities:

QuantityQ /@ q

{True, True, True}

$\endgroup$
  • $\begingroup$ Very nice as always corey $\endgroup$ – Brandon Nov 6 '16 at 17:31
3
$\begingroup$

Quantity and Units are your friends. One way could be:

Clear[sequence];
sequence = RandomReal[{-4, 4}, 3];
d = Map[(N[Round[10^2*#]/(10^2)]) &, sequence]

{3.82,3.64,0.}

Quantity[d, "USD"]

{$ 3.82,$ 3.64,$ 0.}

$\endgroup$
  • $\begingroup$ That's exactly the same approach as in my answer... $\endgroup$ – corey979 Nov 6 '16 at 16:28
  • $\begingroup$ Great Louis. Nice methods from both you and Corey $\endgroup$ – Brandon Nov 6 '16 at 17:32
-1
$\begingroup$
Map[$, N[Round[10^2*#]/(10^2)] & /@ RandomReal[{-4, 4}, 3]]
    (*{$[3.61], $[2.45], $[-1.79]}*)

Is that what you want?

$\endgroup$
  • $\begingroup$ not quite, but I appreciate the response! Very close to the output I was looking for. Check out the 2 other answers above $\endgroup$ – Brandon Nov 6 '16 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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