Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
string
float
communitycreator

How to get the string representation of a float value in Ruby

okwudili onyejiaku

Overview

The to_s method is used to get the string representation of a float value in Ruby. It can also return a NaN, Infinity, or -Infinity, depending on the value of the float.

Syntax

float_value.to_s

Parameters

float_value: This method takes a float value as a parameter.

Return value

This method returns the string representation of the float_value.

Example

# create float values
f1 = 2.333
f2 = -5.777
f3 = -2.0/0.0
f4 = 7.11

# get string representations
s1 = f1.to_s
s2 = f2.to_s
s3 = f3.to_s
s4 = f4.to_s

# print results
puts s1
puts s2
puts s3
puts s4

# check if string
puts "\nAfter Conversion:"
puts "#{f1.class}, #{s1.class}"
puts "#{f2.class}, #{s2.class}"
puts "#{f3.class}, #{s3.class}"
puts "#{f4.class}, #{s4.class}"
Get string representation of float values

Explanation

  • Line 2–5: We create the float values f1, f2, f3, and f4.
  • Line 8–11: We call the to_s method on the float values and store the results in variables s1, s2, s3, and s4.
  • Line 14–17: We print the string representations of the floating point values to the console.
  • Line 21–24: We print the classes of the floating point numbers and their string representations to the console.

RELATED TAGS

ruby
string
float
communitycreator
RELATED COURSES

View all Courses

Keep Exploring