转换字符串“2½” (两个半)变成2.5 [英] Converting String "2½" (two and a half) into 2.5
问题描述
现在,我正在构建一个小型应用程序,该应用程序从电子表格导入数据,由于原始条目的性质,正在读取的字符串的值例如为8½,2½等。
Right now I'm building a small app that imports data from a spreadsheet and due to the nature of the original entry, there is a string being read in that has values such as 8½, 2½, etc.
例如,我的目标是将2½转换为float 2.5。
My goal with a simple function is to convert 2½ into float 2.5, for example.
我尝试了.to_f方法,但是给我留下了2.02½的怪异值。
I've tried the .to_f method but that has left me with a weird value of 2.02½.
这里的任何见解或建议将不胜感激!
Any insight or suggestions here would be very much appreciated!
推荐答案
Unicode仅支持少量的普通分数,这样一个简单的查找表就可以解决问题:
Unicode only supports a small number of vulgar fractions so a simple lookup table will do the trick:
# You might want to double check this mapping
vulgar_to_float = {
"\u00BC" => 1.0 / 4.0,
"\u00BD" => 1.0 / 2.0,
"\u00BE" => 3.0 / 4.0,
"\u2150" => 1.0 / 7.0,
"\u2151" => 1.0 / 9.0,
"\u2152" => 1.0 /10.0,
"\u2153" => 1.0 / 3.0,
"\u2154" => 2.0 / 3.0,
"\u2155" => 1.0 / 5.0,
"\u2156" => 2.0 / 5.0,
"\u2157" => 3.0 / 5.0,
"\u2158" => 4.0 / 5.0,
"\u2159" => 1.0 / 6.0,
"\u215A" => 5.0 / 6.0,
"\u215B" => 1.0 / 8.0,
"\u215C" => 3.0 / 8.0,
"\u215D" => 5.0 / 8.0,
"\u215E" => 7.0 / 8.0,
"\u2189" => 0.0 / 3.0,
}
然后,一点点正则表达式在争吵,以拉动您的
Then, a little bit of regex wrangling to pull your "number" apart:
s = "2½"
_, int_part, vulgar_part = *s.match(/(\d+)?(\D+)?/)
最后,把它们放在一起正确处理正则表达式中可能的 nil
s:
And finally, put them together taking care to properly deal with possible nil
s from the regex:
float_version = int_part.to_i + vulgar_to_float[vulgar_part].to_f
记住 nil.to_i
是 0
和 nil.to_f
是 0.0
。
这篇关于转换字符串“2½” (两个半)变成2.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!