仅当数字少于两个小数位时,才添加.00(至固定) [英] Add .00 (toFixed) only if number has less than two decimal places

查看:36
本文介绍了仅当数字少于两个小数位时,才添加.00(至固定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加零,以便每个数字至少有两个小数,但不能四舍五入.例如:

I need to add zeroes, so that each number has at least two decimals, but without rounding. So for example:

5      --> 5.00
5.1    --> 5.10
5.11   --> 5.11 (no change)
5.111  --> 5.111 (no change)
5.1111 -->  5.1111  (no change) 

我的函数缺少要检查的少于两个小数位的IF:

My function is missing an IF to check for less than two decimal places:

function addZeroes( num ) {
   var num = Number(num);
   if ( //idk ) {
      num = num.toFixed(2);
   }
   return num;
}

谢谢!

除了以下两个以外,还发布其他答案.(请记住,我不是专家,这只是用于文本输入,而不是用于解析复杂的值,例如可能存在浮点问题的颜色,等等.)

Posting an alternative answer, in addition to the two below. (Keep in mind that I'm no expert and this is just for text inputs, not for parsing complex values like colors that could have floating point issues, etc.)

function addZeroes( value ) {
    //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
    var new_value = value*1; //removes trailing zeros
    new_value = new_value+''; //casts it to string

    pos = new_value.indexOf('.');
    if (pos==-1) new_value = new_value + '.00';
    else {
        var integer = new_value.substring(0,pos);
        var decimals = new_value.substring(pos+1);
        while(decimals.length<2) decimals=decimals+'0';
        new_value = integer+'.'+decimals;
    }
    return new_value;
}

[这不是重复的问题.您链接的问题假设知道它们至少有1个小数".文本输入中不能假设小数点,这会出错.]

[This is not a duplicate question. The question you linked assumes "knowing that they have at least 1 decimal." Decimal points cannot be assumed in text inputs, and this was making errors.]

推荐答案

在这里:

function addZeroes(num) {
// Convert input string to a number and store as a variable.
    var value = Number(num);      
// Split the input string into two arrays containing integers/decimals
    var res = num.split(".");     
// If there is no decimal point or only one decimal place found.
    if(res.length == 1 || res[1].length < 3) { 
// Set the number to two decimal places
        value = value.toFixed(2);
    }
// Return updated or original number.
return value;
}

// If you require the number as a string simply cast back as so
var num = String(value);

请参见更新了小提琴进行演示.


edit:自从我第一次回答这个问题以来,javascript和我都取得了进步,这是使用es6的更新解决方案,但遵循相同的想法:


edit: Since I first answered this, javascript and I have progressed, here is an updated solution using es6, but following the same idea:

function addZeroes(num) {
  const dec = num.split('.')[1]
  const len = dec && dec.length > 2 ? dec.length : 2
  return Number(num).toFixed(len)
}

更新了小提琴

这篇关于仅当数字少于两个小数位时,才添加.00(至固定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆