[英]JS or PHP Add Leading Zero to Decimals
I have a form that I'm trying to automatically enforce decimals in some of the input fields. 我有一种表单,试图在某些输入字段中自动强制使用小数。 Basically I would like for the users to not worry about format, but simply have the fields format themselves onBlur. 基本上,我希望用户不必担心格式,而只是将字段本身格式化为onBlur。
Here are a few examples of what I'm hoping to achieve: 以下是一些我希望实现的示例:
1.) If a user enters "0.95" nothing is done, because this is the ultimate format I'm going for in the end. 1.)如果用户输入“ 0.95”,则什么也不做,因为这是我最后要使用的最终格式。
2.) If a user enters ".95" I would like for the field onBlur to change to the above format "0.95". 2.)如果用户输入“ .95”,我希望onBlur字段更改为上述格式“ 0.95”。 (likewise if they enter ".9" etc) (同样,如果他们输入“ .9”等)
I have been scouring around on the internet all night long looking for a solution, so this is my last resort! 我整夜都在互联网上搜寻,以寻求解决方案,所以这是我的最后选择! Any help and feedback I can get would be more than appreciated! 我将获得的任何帮助和反馈将不胜感激!
Thank you! 谢谢!
This is nice and concise: 简洁明了:
function blurFormatDecimal (e) {
var val = isFinite(this.value) ? +this.value : 0;
this.value = val.toFixed(2);
}
myInput.onblur = blurFormatDecimal;
Use isFinite()
instead of !isNaN()
because isNaN("Infinity")
returns false
, but you certainly don't want to accept "Infinity"
as valid input. 使用isFinite()
代替!isNaN()
因为isNaN("Infinity")
返回false
,但是您当然不希望接受"Infinity"
作为有效输入。
http://jsfiddle.net/gilly3/NjeQD/ http://jsfiddle.net/gilly3/NjeQD/
如果需要使用PHP进行此操作,请尝试: $formattedAmount = sprintf("%05.2f",$amount);
这是php解决方案:
$formattedAmount = sprintf("%01.2f",$amount);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.