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

时间:2015-09-03 00:32:33

标签: 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');
});

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

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

此处使用的正则表达式/\.0+$/基本上表示要匹配任何以.开头的字符组,后跟至少一个但最多可以终止于0的{​​{1}}个字符。字符串的结尾。

举个例子:



//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>');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="total_combinado"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

只需在变量前面添加加号(+),就像这样:

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

在您的示例中:

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

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