An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
January 27, 2022 01:55 pm GMT
Original Link: https://dev.to/songta17/how-to-handle-a-price-with-ruby-on-rails-54a0
How to handle a price with Ruby-on-Rails
You surely ever needed to add a price column in a table of your database. But what type to select for the column price? A beginner will try with a float and meet trouble to display the price value.
Use the type Decimal !
Let's create a Book table with title, description and price columns. I put the validations aside, it is not the subject of this tiny article.
rails g model Book title:string author: string price:decimal{8,2}
After making the usual rails db:migrate, launch 'rails c' in the terminal so you can try to create an entry in your database. You can use the next code for convenience :
book = Book.new( title: 'La nuit des temps', author: 'Barjavel', price: 10.99)book.save
No errors right? But your surely see price value like that :
price: 0.1099e2
To display the price with decimal formatted number, you can use .to_s, so we get :
book.price.to_s # 10.99
Done!
Original Link: https://dev.to/songta17/how-to-handle-a-price-with-ruby-on-rails-54a0
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To