Convert string to decimal number in ruby
You call to_i
, you get integer.
Try calling to_f
, you should get a float.
For more string conversion methods, look here.
Ruby convert 2 decimal string into a number and keep the two decimals
Float
You can convert "5565.80" to a float :
value = "5565.80".to_f
# 5565.8
And then display the value with two decimals :
'%.2f' % value
# "5565.80"
A float has double-precision in Ruby, so your value will actually be :
5565.800000000000181898940354...
As a float, you cannot save exactly 5565.80
.
Exact values
Integer
If you want exact values (e.g. for currency), you could use integers for cents :
"5565.80".delete('.').to_i
# 556580
When you need the corresponding float, you could divide it by 100.0
.
Decimal
If you're working with a database, you could use decimal(20,2)
or something equivalent.
BigDecimal
You could also use BigDecimal
:
require 'bigdecimal'
BigDecimal.new("5565.80")
It will save the exact value but will be much slower than int or float.
Ruby Convert String to Decimal
It's maybe not the best way to do it but here is something that works :
"$ 10.80".match(/[0-9|\.]+/)[0].to_f
Ruby on Rails Migration Convert From String To Decimal
What you do is an atomic operation, where first delete the column that you will not use. Then create the column of type decimal. Finally update the table and assign values. If you do not want to lose the information then you should support it through a SQL update procedure converting types. I hope you have served as an orientation. Greetings.
Lo que debes hacer es una operación atómica, donde primero elimines la columna que no vas a utilizar. Luego crear la columna de tipo decimal. Por último actualizar la tabla y asignarle valores. En caso de que no quieras perder la información deberías respaldarla para luego a través de un procedimiento SQL actualicen convirtiendo los tipos. Espero que te haya servido como una orientación. Saludos.
class ChangeOddsAndUnitsColumn < ActiveRecord::Migration
def up
change_table :bets do |t|
t.decimal :units_placed, precision: 16, scale: 2
end
Bets.update_all ["units_placed = ?", 0.0]
end
def down
remove_column :bets, :units_placed
end
end
Strictly convert string to integer (or nil)
Use Integer(string)
It will raise an ArgumentError error if the string cannot convert to an integer.
Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5
You'd still need your number_or_nil method if you want the behavior to be that nil is returned when a string cannot be converted.
def number_or_nil(string)
Integer(string || '')
rescue ArgumentError
nil
end
You should be careful to rescue from a particular exception. A bare rescue (such as "rescue nil") will rescue from any error which inherits from StandardError and may interfere with the execution of your program in ways you don't expect. Integer() will raise an ArgumentError, so specify that.
If you'd rather not deal with exceptions and just prefer a shorter version of your number_or_nil you can take advantage of implicit return values and write it as:
def number_or_nil(string)
num = string.to_i
num if num.to_s == string
end
number_or_nil '5' #=> 5
number_or_nil '5abc' #=> nil
This will work the way you expect.
How to convert a scientific notation string to decimal notation?
Just use string conversion. The necessary coercion to float will be done automatically:
"%f" % "1.0e-05"
=> "0.000010"
# Which, behind the scenes is the same as:
"%f" % "1.0e-05".to_f
=> "0.000010"
Adjust as necessary to get more or less accuracy. For example:
"%.5f" % "1.0e-05"
=> "0.00001"
If you want to get real fancy and chop off unnecessary zeros at the end, here's one way. (Hopefully someone will suggest something more elegant; I couldn't think of anything):
("%.20f" % "1.0e-05").sub(/\.?0*$/, "")
=> "0.00001"
Related Topics
What Does the % Operator Do in Ruby in N % 2
Ruby Merging Two Arrays into One
How Does Rails Implement Before_Filter
Group_By in Rails by 2 or More Attributes
Ruby on Rails and JSON Parser from Url
Error Message "Xcode Alone Is Not Sufficient on Sierra"
Rails 4.2 - Sidekiq Not Sending Emails in Development
Why Is This String Key in a Hash Converted to a Symbol
How to Install Rvm Without Root Access
Build Hash from Collection of Activerecord Models
Error About Nokogiri While Capistrano Deployment on Ubuntu Server
Ruby, Check If Date Is a Weekend
What Are the Things You Would Like Improved in the Ruby Language
What Is the Preferred Way (Better Style) to Name a Namespace in Ruby? Singular or Plural
Heroku Gem Not Working with Rvm
Package Ruby to a Standalone MAC Os X Application
How to Get a List of All Tags While Using the Gem 'Acts-As-Taggable-On' in Rails (Not the Counts)