Using jQuery to display a value to 2 decimal places in an input box while retaining more precision [duplicate]
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
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 r开发者_JAVA百科emain as 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.
num = 12.434234234;
result = num.toFixed(2); // returns 12.43
You can store the fine-grained values in hidden fields, and trim the ones displayed for the user.
You could store the value of the input as data
of the input (using jQuery), format it onload and then replace the value during submit
like so:
http://jsfiddle.net/magicaj/8cdRs/1/
HTML:
<form id="form">
<input type="text" class="formatted-number-input" value="12.434234234" />
</form>
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);
});
});
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.
精彩评论