简体   繁体   English

如何在 javascript/typescript 中将数字转换为 double 数据类型?

[英]How to convert a number to double data type in javascript/ typescript?

I have one input filed where the user can enter any numbers eg: 12 12.1 12.30 12.34 I have to pass this value in a service call here i can only send the value as number but with 2 decimal points我有一个输入字段,用户可以在其中输入任何数字,例如: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);

EXAMPLE例子

//input is 12
a=12
b="12.00"
c=12

//input is 12.30
a=12.30
b="12.30"
c=12.3

I want a method, using which i can input a value as a number and output will be number with 2 decimal points.我想要一种方法,使用它我可以输入一个值作为数字,输出将是带有 2 个小数点的数字。

If you want a number to always display in two decimal places, you can do as below.如果你想让一个数字始终显示在小数点后两位,你可以这样做。 It will round all the numbers to two decimal places(including doubles).它将所有数字四舍五入到小数点后两位(包括双精度数)。

function twoDecimal(yourNumber){
    return parseFloat(Math.round(yourNumber * 100) / 100).toFixed(2);
}

let x=twoDecimal(10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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