1

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

Ratatouille
  • 1,284
  • 3
  • 19
  • 46
  • @CarySwoveland the OP is looking for a solution using `sprintf` which returns strings. – Stefan Nov 07 '14 at 16:59
  • @Stefan, considering that the OP first tried to use a regex, I figure this is an XY question with the current focus being on `sprintf`, but I will ask (and will delete my earlier comment. – Cary Swoveland Nov 07 '14 at 17:30
  • Ratatouille, is your question how to convert the float `21.95` to the string `".95" `, or how to do that using `sprintf`? Your first line is confusing because `.95` is not shown in quotes. – Cary Swoveland Nov 07 '14 at 17:37

2 Answers2

2

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.

Community
  • 1
  • 1
Bibek Shrestha
  • 30,149
  • 7
  • 30
  • 33
0

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.

Qwedvit
  • 237
  • 3
  • 11