日期:2014-05-16  浏览次数:20353 次

js,jquery,php 对小数点的处理

js,jquery,php 对小数点的处理

jquery

?

function?regInput(obj,?reg,?inputStr)
?{
??var?docSel?=?document.selection.createRange()
??if?(docSel.parentElement().tagName?!=?"INPUT")?return?false
??oSel?=?docSel.duplicate()
??oSel.text?=?""
??var?srcRange?=?obj.createTextRange()
??oSel.setEndPoint("StartToStart",?srcRange)
??var?str?=?oSel.text?+?inputStr?+?srcRange.text.substr(oSel.text.length)
??return?reg.test(str)
?}


?
<INPUT?style="WIDTH:?50px;IME-MODE:disabled"?value=0?name=flightback?min="0"?max="99"?onKeyPress?=?"return?regInput(this,/^\d*\.?\d{0,2}$/,String.fromCharCode(event.keyCode))">?%

?

?

JS保留两位小数(非强制)?
对于一些小数点后有多位的浮点数,我们可能只需要保留2位,但js没有提供这样直接的函数,所以我们得自己写函数实现这个功能,代码如下:
function?changeTwoDecimal(x)
{
var?f_x?=?parseFloat(x);
if?(isNaN(f_x))
{
alert('function:changeTwoDecimal->parameter?error');
return?false;
}
var?f_x?=?Math.round(x*100)/100;

return?f_x;
}

功能:将浮点数四舍五入,取小数点后2位
用法:changeTwoDecimal(3.1415926)?返回?3.14
changeTwoDecimal(3.1475926)?返回?3.15



js保留两位小数
realprice=price*discount/10;

$('#dish_realpri').attr("value",realprice.toFixed(2))

php保留两位小数
$yuanpri=$rows['dish_price']/$rows['dish_discount']*10; if (ceil($yuanpri) == $yuanpri) { echo $yuanpri; }else { echo floor($yuanpri*100)/100; }