admin管理员组文章数量:1394051
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
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.
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
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.
Share Improve this question asked Jul 28, 2017 at 21:35 Aswin KVAswin KV 1,7602 gold badges14 silver badges24 bronze badges 4-
3
All numeric types in typescript are
number
which are floating point values, so I don't think data type conversion is what you're after here. Seems like you just want to take any number and round/truncate it or right-pad w/ zeroes to two digits. typescriptlang/docs/handbook/basic-types.html – JBC Commented Jul 28, 2017 at 21:40 -
2
You can try getting the value of your input,
parseFloat
it and thentoFixed
it – Lixus Commented Jul 28, 2017 at 21:42 -
"Double" does not mean two decimal places, it means double precision. There is no way to specify a number to a fixed number of places except to store it as a string using
.toFixed
. That's the whole reason that method returns a string in the first place. – Jared Smith Commented Jul 28, 2017 at 21:49 -
Actually, you may want to use toExponential method, so you can store your
12.30
number as1230e-2
and don't loose that zero. – Maxim Mazurok Commented Jul 28, 2017 at 21:56
1 Answer
Reset to default 2If 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);
本文标签: angularHow to convert a number to double data type in javascript typescriptStack Overflow
版权声明:本文标题:angular - How to convert a number to double data type in javascript typescript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744089033a2589080.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论