我有一个输入字段,用户可以输入任何数字 例如:12 12.1 12.30 12.34 我必须在服务调用中传递此值,我只能将值作为数字发送,但带有2个小数点
let a = input //a will be a type of number
let b = a.toFixed(2) //b will be type of string
let c = Number(b) //it will automatically cut unwanted '0'
console.log(c);
示例
//input is 12
a=12
b="12.00"
c=12
//input is 12.30
a=12.30
b="12.30"
c=12.3
我想要一个方法,使用该方法我可以输入一个数字作为数字,输出将是2位小数的数字。
答案 0 :(得分:0)
如果您希望数字始终以小数点后两位显示,则可以执行以下操作。它会将所有数字四舍五入到小数点后两位(包括双精度数)。
function twoDecimal(yourNumber){
return parseFloat(Math.round(yourNumber * 100) / 100).toFixed(2);
}
let x=twoDecimal(10);