Skip to content
Permalink
Browse files

Merge pull request #494 from cptobvious/string-to_f

String#to_f
  • Loading branch information
alex committed Mar 11, 2013
2 parents 34bb018 + 61132cd commit 14a4f6f25d626b1decb73e9e1249bee75f1cb015
Showing with 68 additions and 0 deletions.
  1. +16 −0 tests/objects/test_stringobject.py
  2. +52 −0 topaz/objects/stringobject.py
@@ -289,6 +289,22 @@ def test_to_i(self, space):
with self.raises(space, "ArgumentError"):
space.execute('"".to_i(37)')

def test_to_f(self, space):
w_res = space.execute('return "123.45".to_f')
assert space.float_w(w_res) == 123.45

w_res = space.execute('return "45.67 degrees".to_f')
assert space.float_w(w_res) == 45.67

w_res = space.execute('return "thx1138".to_f')
assert space.float_w(w_res) == 0.0

w_res = space.execute('return "123.45e1".to_f')
assert space.float_w(w_res) == 1234.5

w_res = space.execute('return " 123.45e1".to_f')
assert space.float_w(w_res) == 1234.5

def test_swapcase(self, space):
w_res = space.execute("""
a = "AbC123aBc"
@@ -1,5 +1,6 @@
import copy
import string
import math

from rpython.rlib import jit
from rpython.rlib.objectmodel import newlist_hint, compute_hash
@@ -720,6 +721,57 @@ def method_to_i(self, space, radix=10):
else:
return space.newint(value)

@classdef.method("to_f")
def method_to_f(self, space):
# can't use rstring_to_float here because of rpython?

value = 0.0
precision = False
pointer = 0.1
negative = False
exponent = False
multi = 0
number = False

for char in space.str_w(self):
c = ord(char)
if ord("0") <= c <= ord("9"):
if exponent:
multi = multi * 10 + c - ord("0")
elif precision:
value = value + pointer * (c - ord("0"))
pointer /= 10
else:
value = value * 10 + c - ord("0")

number = True
elif c == ord("-"):
if value != 0.0:
break
negative = not negative
elif c == ord("+"):
if value != 0.0:
break
pass
elif c == ord("."):
if precision or exponent:
break
precision = True
elif c == ord("e"):
if exponent:
break
exponent = True
elif char.isspace():
if number:
break
else:
break

if exponent:
value = value * math.pow(10, multi)

return space.newfloat(value)

@classdef.method("tr", source="str", replacement="str")
def method_tr(self, space, source, replacement):
string = self.copy(space)

0 comments on commit 14a4f6f

Please sign in to comment.
You can’t perform that action at this time.