Ratatouille
Ratatouille

Reputation: 1492

show only decimal value in floating point number using sprintf

I'm been trying to get only decimal point value of a floating point number here are my sceanrio

21.95 => .95

22.00 => .00

I try do it using following regex

\.\d{2}

I even had other solution

number = 21.96.round(2)

precision = number - number.to_i

Or

"." + number.to_s.split('.')[1]

But I'm just not able to find it via sprintf which is what I want

Upvotes: 1

Views: 1099

Answers (2)

Bibek Shrestha
Bibek Shrestha

Reputation: 35034

You can only get the decimal part using the module function. Here is a solution using sprintf

a = 1001.123123
sprintf("%.2f", a.modulo(1))
# prints 0.12

Without sprintf,

a = 1001.123123
puts a.modulo(1).round(2)
# prints 0.12

Related question to get the fraction part here and more about the modulo function here.

Upvotes: 2

Qwedvit
Qwedvit

Reputation: 247

I think its best to approach this problem from a char point of view. First convert your double to an array of chars, then check each character if the value of that character is a ".". Next you just put the following characters into a string and output these in sprintf.

Upvotes: 0

Related Questions