简体   繁体   English

格式化价格输入

[英]Formatting Price Input

ideally this is for AS3, but I can always convert it down from JavaScript.理想情况下,这是针对 AS3 的,但我始终可以将其从 JavaScript 转换下来。 Basically I want type numbers into a field and have it add the decimal.基本上我想在一个字段中输入数字并让它添加小数。 The issue is, the keyboard won't have a "."问题是,键盘不会有“。” key钥匙

So if the final output was 10.45所以如果最终输出是 10.45

it would automatically start to format as I type:它会在我输入时自动开始格式化:

1 it would change to .01. 1 它将更改为 0.01。 And as I keep typing.. .01当我继续打字时....01
.10 .10
10.40 10.45 10.40 10.45

This can be accomplished by some simple string manipulation.这可以通过一些简单的字符串操作来完成。 Just split the string into parts and insert the decimal.只需将字符串分成几部分并插入小数。

HTML HTML

<input type="text" id="price" onchange="formatPrice(this)" />

Javascript Javascript

function formatPrice(obj) {
    //remove any existing decimal
    p = obj.value.replace('.','');

    //get everything except the last 2 digits
    var l = p.substring(-2, p.length-2);

    //get the last 2 digits
    var r = p.substring(p.length-2,p.length);

    //update the value
    obj.value = l + '.' + r;
}

You can see it working here: https://jsfiddle.net/x3wey5uk/你可以在这里看到它的工作: https : //jsfiddle.net/x3wey5uk/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM