简体   繁体   中英

I want my value modified to always have three decimal digits

My logic calculates and returns a value based on user input, I want to modify that value to always have three decimal digits

For example;

1 to 1.000
1.02 to 1.020
2.000004 to 2.000
2.5687 to 2.569

How would I achieve it on javascript?

You can use Number().toFixed() to do it

 const formatVal = (val,precise = 3) =>{ return Number(val).toFixed(precise) } console.log(formatVal(1,3)) console.log(formatVal(1.02,3)) console.log(formatVal(2.000004,3)) console.log(formatVal(2.5687)) console.log("-----------------") console.log(formatVal(2.5687,2))

You can do something like this,

 let newNum = Number(1.34).toFixed(3); console.log(newNum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM