使用jquery显示小数,但如果小数为零则不显示



我有这段代码,并按预期工作,但我需要隐藏小数,如果是像。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');
});

任何想法?

如果您想在所有的尾位数字为0的情况下仅删除,最简单的方法可能是使用.replace(/.0+$/,'')

这里使用的正则表达式/.0+$/基本上表示匹配以.开头的任何一组字符,后跟至少一个但不超过任意数量的0 s,并以字符串结尾结束。

例如:

//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>

只需在变量前面加上+ (+):

var number = 1.3000001;
var total = +number.toFixed(2);

在你的例子中:

$('#peso_total').val(+peso_combinado.toFixed(4));

来源:https://javascript.info/number

.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');
});

最新更新