How to format an array

L

Li Chen

Hi all,

I have an array [1.0, 2.0, 3, 4,5,6]. I want to format all the elements
within the array into to this format "%5.3f", that is 5
spaces/characters for each number/element, followed by 3 floating
points. Any help will be appreciate.

Li
 
N

Noah Easterly

[1.0, 2.0, 3, 4,5,6].map { |num| "%5.3f" % num } #=> ["1.000", "2.000",
"3.000", "4.000", "5.000", "6.000"]
 
P

Peter Szinek

Hello,

Li said:
Hi all,

I have an array [1.0, 2.0, 3, 4,5,6]. I want to format all the elements
within the array into to this format "%5.3f", that is 5
spaces/characters for each number/element, followed by 3 floating
points. Any help will be appreciate.

[1.0, 2.0, 3, 4,5,6].map { |n| sprintf "%5.3f", n }

Peter
http://www.rubyrailways.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,215
Messages
2,571,113
Members
47,713
Latest member
LeliaB1379

Latest Threads

Top