1

How can we obtain formatted output using p function. of ruby. I need to print a float with exactly two decimal places. I want to do it using minimum characters so i want to use p function instead of puts and printf.

i have tried this printf"%.2f",a.abs/2 Any idea on how to reduce characters ?

1

3 Answers 3

1

inspect is the method you need to override for p

class Float
  def inspect
    sprintf "%.2f", self
  end
end

Result

p 12.0
#=> 12.00
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you're ok about a string being returned, you can use use Kernel#sprintf

sprintf "%.2f", 1.234
=> "1.23"

Note that printf is really just sugar for IO.write(sprint()) so the above should be considered equiavelent.

2 Comments

I want to reduce number of characters , sprintf is having more
I don't understand your point. What do you want to reduce exactly?
0

You can use the method String#%

str % arg → new_str

Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string.

In your example:

a = 5.3
p"%.2f"%a

If you use a formula you need additional braces:

p"%.2f"%(a.abs/2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.