12

I want to use this helper method on controller. Any way to achieve this?

Ravindra S
  • 6,302
  • 12
  • 70
  • 108
mlzboy
  • 14,343
  • 23
  • 76
  • 97
  • On a broader sense, requiring View Helpers in Controller is bad design. But sometimes the system mandates it. So if you post some code on how you intend to use it, it'll be helpful. A quick, but dirty and not recommended way is to use `include ActionView::Helper` in your controller. – Swanand Dec 13 '10 at 06:39
  • Related if not duplicate: http://stackoverflow.com/questions/15733971/how-do-i-require-numberhelper-and-make-it-work – Andrew Grimm Jan 18 '16 at 00:32

2 Answers2

30

Probably not a great idea, but if you must, include the helper like so:

class WhateverController
  include ActionView::Helpers::NumberHelper

  def show
    render :text => number_with_precision(2342.234, :precision => 2)
  end

end
jenjenut233
  • 1,938
  • 16
  • 13
7

A much better way to control number precision is rails controllers is to use sprintf

"%.2f" % 2342.234 => "2342.23"
"%.6f" % 2342.234 => "2342.234000"
Mark Oliver
  • 79
  • 1
  • 2