Javascript 使用 jQuery 在输入框中显示 2 个小数位的值,同时保持更高的精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5320098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:38:53  来源:igfitidea点击:

Using jQuery to display a value to 2 decimal places in an input box while retaining more precision

javascriptjqueryhtmlformattingnumbers

提问by John Hunt

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

可能的重复:
JavaScript:用两位小数格式化数字

Maybe I'm going about this the wrong way, but I have some javascript which is filling up some text inputs with numbers like 12.434234234. I want the text input to only display 12.43, but I'd like it's value to remain as 12.434234234.

也许我用错误的方式来解决这个问题,但是我有一些 javascript,它用 12.434234234 之类的数字填充了一些文本输入。我希望文本输入只显示 12.43,但我希望它的值保持为 12.434234234。

Is this even possible? If not, what would be the best work-around?

这甚至可能吗?如果没有,最好的解决方法是什么?

Thanks! John.

谢谢!约翰。

--

——

Although there were some very good answers here, I was looking for something like 'why don't you just use this clever one liner thing..' - hence I've ticked the most basic approach which is to just use an extra field. Thanks though! Marked up all answers.

尽管这里有一些非常好的答案,但我一直在寻找诸如“为什么不使用这种聪明的衬里之类的东西..”之类的东西 - 因此我勾选了最基本的方法,即只使用一个额外的字段。不过还是谢谢!标记了所有答案。

回答by Mike Lewis

num = 12.434234234;
result = num.toFixed(2); // returns 12.43

回答by weltraumpirat

You can store the fine-grained values in hidden fields, and trim the ones displayed for the user.

您可以将细粒度值存储在隐藏字段中,并修剪为用户显示的值。

回答by Adam Ayres

You could store the value of the input as dataof the input (using jQuery), format it onload and then replace the value during submitlike so:

您可以将输入的值存储为data输入(使用 jQuery),在加载时对其进行格式化,然后submit像这样替换值:

http://jsfiddle.net/magicaj/8cdRs/1/

http://jsfiddle.net/magicaj/8cdRs/1/

HTML:

HTML:

<form id="form">
    <input type="text" class="formatted-number-input" value="12.434234234" />
</form>

JS:

JS:

$(".formatted-number-input").each(function() {
   var value = $(this).val(); 
   $(this).data("originalValue", value);
   var roundedValue = value.toFixed(2);
   $(this).val(roundedValue);
});

$("#form").submit(function() {    
    var formattedInput = $(".formatted-number-input");
    formattedInput.each(function() {
        var originalValue = $(this).data("originalValue");
        $(this).val(originalValue);
    });
});

回答by anazimok

There are multiple ways to solve this problem: 1. Create hidden field, store 12.434234234 in it and display formatted value in textfield. 2. Store original 12.434234234 using jquery.data() and display formatted value in textfield.

有多种方法可以解决这个问题: 1. 创建隐藏字段,在其中存储 12.434234234 并在文本字段中显示格式化的值。2. 使用 jquery.data() 存储原始 12.434234234 并在文本字段中显示格式化值。