Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第1365天 使用js写一个方法,四舍五入保留2位小数(不够位数,则用0替补) #5322

Open
haizhilin2013 opened this issue Jan 9, 2023 · 4 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第1365天 使用js写一个方法,四舍五入保留2位小数(不够位数,则用0替补)

3+1官网

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label Jan 9, 2023
@Bukuchengkuyuan
Copy link

function main (val){
    let value = val.toString().split('.');
    if (value.length === 2){
        let t = value[1];
        let small = t;
        if (t.length > 2){
            if (t.charAt(2) === '5'){
                small = (t.substr(0, 2) + '9');
            }
        }
        return Number(value[0] + '.' + small).toFixed(2);
    }else{
        return value[0]+'.00';
    }
}

@kbjing
Copy link

kbjing commented Feb 17, 2023

数字.toFixed(2) ???这样回答算吗

@ShihHsing
Copy link

function roundToTwoDecimalPlaces(num) {
  if (isNaN(num)) {
    return '';
  }
  const roundedNum = Math.round(num * 100) / 100;
  const parts = roundedNum.toFixed(2).split('.');
  const integerPart = parts[0];
  const decimalPart = parts.length > 1 ? parts[1] : '00';
  const padding = '0'.repeat(2 - decimalPart.length);
  return integerPart + '.' + decimalPart + padding;
}

函数接受一个数字参数 num,并返回四舍五入到两个小数位的字符串。如果参数不是数字,则返回一个空字符串。

函数内部首先使用 Math.round() 函数将数字四舍五入到两个小数位。然后使用 toFixed() 函数将其转换为字符串,并将其分成整数部分和小数部分。如果小数部分不存在,则使用字符串 '00' 代替。最后将小数部分填充到两位。最终,将整数部分和小数部分组合在一起,并用小数点分隔它们返回结果字符串。

@ShihHsing
Copy link

数字.toFixed(2) ???这样回答算吗

可以是可以 碰到String类型的入参会嘎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

4 participants