float php 下取_PHP: Float 浮点型 - Manual

这是一个PHP函数,用于将科学计数法(如1.6e+12)转换为标准的十进制数(如1600000000000)。函数首先确保输入是一个标准的PHP浮点数字符串,然后解析数字和指数部分,计算出正确的零数,并根据正负指数添加前导零或尾随零。对于不同类型的指数表示,例如1.6E+6和-4.566e-12,函数都能正确处理。
摘要由CSDN通过智能技术生成

Here is a function to convert an exponential-format float to a decimal-format float; e.g. 1.6e+12 to 1600000000000.

It will help addressing the problem specified by kjohnson above.

I have tested it, but not in any real world situation so any feedback/improvements/bug-reports would be appreciated.

// e.g. '1.6E+6' to '1600000', '-4.566e-12' to '-0.000000000004566', '+34e+10' to '340000000000'

// Author: Bob{// make sure its a standard php float string (i.e. change 0.2e+2 to 20)

// php will automatically format floats decimally if they are within a certain range$float_str= (string)((float)($float_str));// if there is an E in the float stringif(($pos=strpos(strtolower($float_str),'e')) !==false)

{// get either side of the E, e.g. 1.6E+6 => exp E+6, num 1.6$exp=substr($float_str,$pos+1);$num=substr($float_str,0,$pos);// strip off num sign, if there is one, and leave it off if its + (not required)if((($num_sign=$num[0]) ==='+') || ($num_sign==='-'))$num=substr($num,1);

else$num_sign='';

if($num_sign==='+')$num_sign='';// strip off exponential sign ('+' or '-' as in 'E+6') if there is one, otherwise throw error, e.g. E+6 => '+'if((($exp_sign=$exp[0]) ==='+') || ($exp_sign==='-'))$exp=substr($exp,1);

elsetrigger_error("Could not convert exponential notation to decimal notation: invalid float string '$float_str'",E_USER_ERROR);// get the number of decimal places to the right of the decimal point (or 0 if there is no dec point), e.g., 1.6 => 1$right_dec_places= (($dec_pos=strpos($num,'.')) ===false) ?0:strlen(substr($num,$dec_pos+1));// get the number of decimal places to the left of the decimal point (or the length of the entire num if there is no dec point), e.g. 1.6 => 1$left_dec_places= ($dec_pos===false) ?strlen($num) :strlen(substr($num,0,$dec_pos));// work out number of zeros from exp, exp sign and dec places, e.g. exp 6, exp sign +, dec places 1 => num zeros 5if($exp_sign==='+')$num_zeros=$exp-$right_dec_places;

else$num_zeros=$exp-$left_dec_places;// build a string with $num_zeros zeros, e.g. '0' 5 times => '00000'$zeros=str_pad('',$num_zeros,'0');// strip decimal from num, e.g. 1.6 => 16if($dec_pos!==false)$num=str_replace('.','',$num);// if positive exponent, return like 1600000if($exp_sign==='+') return$num_sign.$num.$zeros;// if negative exponent, return like 0.0000016else return$num_sign.'0.'.$zeros.$num;

}// otherwise, assume already in decimal notation and returnelse return$float_str;

}?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值