Javascript将轮数应用于其他值

时间:2018-08-02 08:27:05

标签: javascript

我被开发人员失望了,我有一个非常基本的问题,希望您能够回答。

Image

您可以在图像上看到,“ Cashflow annuel”的值未四舍五入,并且从我当前拥有的脚本中了解到的是,我需要使用的功能是:Cash = Cash.toFixed (1);

但是我不知道如何将其应用于结果“ Cashflow annuel”。

我知道这可能是非常基础的,但是我绝对没有编码技能。

以下是完整的脚本,因此您可以了解我在说什么:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    <script>
    jQuery(document).ready(function () {
        jQuery('#cashflow').validate({ // initialize the plugin
            rules: {
                loyer_mensuel: "required",
                charges_rec: "required",
                mensualites: "required",
                charges_copro: "required",
                taxe_fonc: "required",
                autres_charges: "required"
            },
           debug: true,
            messages: {
                loyer_mensuel: "Champ obligatoire",
                charges_rec: "Champ obligatoire",
                mensualites: "Champ obligatoire",
                charges_copro: "Champ obligatoire",
                taxe_fonc: "Champ obligatoire",
                autres_charges: "Champ obligatoire"
            },
            submitHandler: function (form) { 
                event.preventDefault();
                loyer_mensuel = Number($("#loyer_mensuel").val());
                charges_recup = Number($("#charges_rec").val());
                mensualites = Number($("#mensualites").val());
                charges_copro = Number($("#charges_copro").val());
                taxe_fonciere = Number($("#taxe_fonc").val());
                autres_charges = Number($("#autres_charges").val());
                cash = (loyer_mensuel + charges_recup) - (mensualites + charges_copro + (taxe_fonciere/12) + autres_charges );
cash = cash.toFixed(1);
                jQuery('#cashflow-mensuel').val(cash + ' € / mois');
                jQuery('#cashflow-annuel').val(cash*12 + ' € / an');

            }
        });
});
</script>

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

使用Math.round()可以解决问题。

jQuery('#cashflow-annuel').val(Math.round(cash*12) + ' € / an');

答案 1 :(得分:0)

@FabienGreard提出的答案是正确的,但您有多种选择可能会很有趣

Math.round()

此功能会将您的数字四舍五入到最接近的整数,因此您永远不会有十进制数字

jQuery('#cashflow-annuel').val(Math.round(cash*12) + ' € / an');
//Output ==> -6766

如果您想用货币值常用的小数点四舍五入,则可以使用以下

//Math.round(num * 100) / 100
jQuery('#cashflow-annuel').val((Math.round((cash*12)*100) / 100) + ' € / an');
//Output ==> -6765.6

Number.toFixed()

在您的问题中,您建议使用toFixed(1)。此功能会将您的数字转换成代表带有1个小数的数字的字符链

jQuery('#cashflow-annuel').val((cash*12).toFixed(1) + ' € / an');
//Output ==> "-6766.0"