# How to format an array

**URL:** <https://www.ruby-forum.com/t/how-to-format-an-array/72915>\
**Category:** Ruby\
**Created:** [October 19, 2006, 9:49pm UTC](https://www.ruby-forum.com/t/how-to-format-an-array/72915 "2006-10-19T21:49:06Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 19, 2006, 9:49pm UTC](https://www.ruby-forum.com/t/how-to-format-an-array/72915/1 "2006-10-19T21:49:06Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 19, 2006, 10:01pm UTC](https://www.ruby-forum.com/t/how-to-format-an-array/72915/2 "2006-10-19T22:01:14Z")

</div>

[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”]

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 19, 2006, 10:05pm UTC](https://www.ruby-forum.com/t/how-to-format-an-array/72915/3 "2006-10-19T22:05:15Z")

</div>

Hello,

Li Chen wrote:

> 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](http://www.rubyrailways.com)

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [October 20, 2006, 5:30pm UTC](https://www.ruby-forum.com/t/how-to-format-an-array/72915/4 "2006-10-20T17:30:15Z")

</div>

On 10/19/06, Li Chen [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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.

might not be the best solution, but hey it’s different from the others:

ar = [1.0, 2.0, 3, 4, 5, 6]  
p sprintf "%5.3f " \* ar.length, \*ar
