Message Boards Message Boards

0
|
3186 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Apply NumberForm[] to part of list

Posted 3 years ago

Consider the list

{
{1 , 38.58367},
{2 , 95.837674},
{3 , 84,183247},
{4 , 20.286123},
}

I want to use NumberForm[#,3] on the "second column" only so to get

{
{1 , 38.6},
{2 , 95.8},
{3 , 84,1},
{4 , 20.2},
}

I.e.,

NumberForm[38.58367,3]
(*38.6*)
NumberForm[95.837674, 3]
(*95.8*)
etc.

How can I do that?

I saw the documentation for MapAt which says something a bit close:

Map f onto the second element of all top-level parts (the "second column"):

MapAt[f, {{a, b, c}, {d, e}}, {All, 2}]
(*{{a, f[b], c}, {d, f[e]}}*)

But I don't think it helps because NumberForm doesn't have an "Operator form".

Any help would be appreciated!

POSTED BY: Ehud Behar
3 Replies
Posted 3 years ago

Hi Ehud,

It is always possible to write a pure function that behaves like an operator form. I think there is a typo in the third element of the list should be 84.183247, not 84, 183247. I made that change

list = {{1, 38.58367}, {2, 95.837674}, {3, 84.183247}, {4, 20.286123}}

MapAt[NumberForm[#, 3] &, list, {All, {2}}]
(* {{1, 38.6}, {2, 95.8}, {3, 84.2}, {4, 20.3}} *)

Or

{First@#, NumberForm[Last@#, 3]} & /@ list

Or

list /. {a_, b_} :> {a, NumberForm[b, 3]}
POSTED BY: Rohit Namjoshi
Posted 3 years ago

@Rohit Namjoshi Thanks a lot!

You always come up with clear and simple solutions.

POSTED BY: Ehud Behar

Hope that is what you need

POSTED BY: Ahmed Elbanna
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract