我有这个代码,和可以正常工作,但是如果像.0000这样,我需要隐藏小数,现在我使用的是.toFixed,但它呈现的是零而不是什么
$('#peso_combinado').keyup(function() {
var peso_combinado = $('#peso_combinado').val();
var cantidad = Number($('#sacos').val());
var peso_tara = Number($('#peso_tara').val());
var medividen = 0;
var total_tara = 0;
var neto_total = 0;
total_tara = peso_tara * cantidad;
medividen = peso_combinado / cantidad;
neto_total = (peso_combinado - total_tara) / 100;
$('#peso_total').val(peso_combinado.toFixed(4));
$('#total_tara').val(total_tara.toFixed(4));
$('#peso_neto').val(neto_total.toFixed(4));
$('.total_combinado').val(medividen.toFixed(4));
$('#total_por_saco').attr('name', '');
$('.total_combinado').attr('name', 'peso_proporcional');
$('#total_por_saco').attr('id', '');
$('.total_combinado').attr('id', 'peso_proporcional');
});有什么想法吗?
发布于 2015-09-03 09:28:21
如果您希望仅在尾随数字的所有都为0的情况下删除它们,则最简单的方法可能是使用.replace(/\.0+$/,'')
这里使用的正则表达式/\.0+$/基本上表示匹配任何以.开头的字符组,后跟至少一个但不超过任意数量的以字符串结尾终止的0。
举个例子:
//when float has only 0s after the decimal place, replace them
var medividen = 46.0000
$('.total_combinado').append(medividen.toFixed(4).replace(/\.0+$/,'') +'<br>');
//wont affect floats that do have digits other than 0 after the decimal
medividen = 46.3400
$('.total_combinado').append(medividen.toFixed(4).replace(/\.0+$/,'')+'<br>');
//also wont hurt floats that start with 00 but then have other numbers
medividen = 46.0034
$('.total_combinado').append(medividen.toFixed(4).replace(/\.0+$/,'')+'<br>');<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="total_combinado"></div>
发布于 2019-07-05 01:52:46
只需在变量前面添加加号(+),如下所示:
var number = 1.3000001;
var total = +number.toFixed(2);在您的示例中:
$('#peso_total').val(+peso_combinado.toFixed(4));发布于 2015-09-03 09:28:44
.toFixed(x)返回一个字符串。只需再次将其解析为浮点数:
function tofixed(val) {
return parseFloat(val.toFixed(4));
}
$('#peso_combinado').keyup(function () {
var peso_combinado = $('#peso_combinado').val();
var cantidad = Number($('#sacos').val());
var peso_tara = Number($('#peso_tara').val());
var medividen = 0;
var total_tara = 0;
var neto_total = 0;
total_tara = peso_tara * cantidad;
medividen = peso_combinado / cantidad;
neto_total = (peso_combinado - total_tara) / 100;
$('#peso_total').val(tofixed(peso_combinado));
$('#total_tara').val(tofixed(total_tara));
$('#peso_neto').val(tofixed(neto_total));
$('.total_combinado').val(tofixed(medividen));
$('#total_por_saco').attr('name', '');
$('.total_combinado').attr('name', 'peso_proporcional');
$('#total_por_saco').attr('id', '');
$('.total_combinado').attr('id', 'peso_proporcional');
});https://stackoverflow.com/questions/32365246
复制相似问题