在Python中找到小数点后面的数字

时间:2017-10-01 07:52:24

标签: python

如何在小数点后找到这样的数字:123.44小数部分的第一个数字是4.我怎样才能在python中找到它?

4 个答案:

答案 0 :(得分:5)

最简单的方法,根据public function do_upload($uploadedField, $employeeID) { //$uploadedField = $this -> input -> post('_hidden_field'); if (empty($_FILES[$uploadedField]['name'])) { $error = "File is empty please choose a file"; return $error; } else { $name = '_' . $uploadedField; $config['file_name'] = $employeeID . $name; $config['upload_path'] = './uploads/' . $employeeID; $config['allowed_types'] = 'gif|jpg|jpeg|png|iso|dmg|zip|rar|doc|docx|xls|xlsx|ppt|pptx|csv|ods|odt|odp|pdf|rtf|sxc|sxi|txt|exe|avi|mpeg|mp3|mp4|3gp'; $config['max_size'] = 2048; $config['max_width'] = 0; $config['max_height'] = 0; $this -> load -> library('upload', $config); if (!is_dir('uploads')) { mkdir('./uploads', 0777, true); } $dir_exist = true; // flag for checking the directory exist or not if (!is_dir('uploads/' . $employeeID)) { mkdir('./uploads/' . $employeeID, 0777, true); $dir_exist = false; // dir not exist } else { } if (!$this -> upload -> do_upload($uploadedField)) { if (!$dir_exist) rmdir('./uploads/' . $employeeID); $error = array('error' => $this -> upload -> display_errors()); return $error; //$this -> load -> view('upload_form', $error); } else { $data = array('upload_data' => $this -> upload -> data()); return $path = $data['upload_data']['full_path']; } } } 将数字转换为str,然后转换为split。我已经在下面进行了每次迭代。

'.'

注意:这里,如果数字不是小数点,则会抛出>>> num=123.44 >>> str(num).split('.') => ['123', '44'] >>> str(num).split('.')[1] => '44' >>> str(num).split('.')[1][0] => '4' >>> int(str(num).split('.')[1][0]) => 4 。因此,您可以通过执行以下操作来检查它是否存在:

Error

所以,>>> str(num).find('.') #num=123.44 3 >>> str(num).find('.') #num=123 -1 条件是:

if

,只需使用>>> if str(num).find('.') >= 0 : #has decimal point

答案 1 :(得分:2)

最简单的可能是乘以10,然后转换为整数并进行模10操作:

int(number * 10) % 10

答案 2 :(得分:1)

执行此操作的一个简短方法是不抛出错误并使用负数,这是下面的代码。它也不要求您导入任何库:

after_point = num - int(num)
10*round(after_point, 1)

这样,如果小数点后面没有任何内容,您将获得0

答案 3 :(得分:0)

这是一个不涉及拆分字符串的解决方案。这个使用for循环代替。

num = 123.44
after_dec_num = -1
has_seen_point = False
for digit in str(num):
    if digit == '.':
        has_seen_point = True
    elif has_seen_point:
        after_dec_num = int(digit)
        break

print(after_dec_num)

一旦找到小数点后面的数字,我们就会得到那个数字并且循环将停止。如果数字没有小数点,我们会改为-1

替代方案如下所示。

num = 123.44
after_dec_num = -1
number = str(num)
for idx in range(len(number)):
    if number[idx] == '.':
        # Since we have a decimal point, we can always assume
        # that there would be a number after it.
        after_dec_num = int(number[idx + 1])
        break

这个使用索引可以轻松地检索后续数字。结果将是前面的循环。

相关问题