简体   繁体   English

如何将数字转换为浮点数

[英]How to transform number to float

So for rounding I use 所以我用四舍五入

Math.round(num * 100) / 100;

But I also need the decimals like this 但是我也需要这样的小数

1 => 1.00
1.5 => 1.50
1.456 => 1.46

I achieve this with 我做到了

 num.toFixed(2);

but this returns a string, I know this has to be a string. 但这返回一个字符串,我知道这必须是一个字符串。 However is there a way to get the same functionality but returning float values, not string? 但是,有一种方法可以获取相同的功能,但返回浮点值,而不是字符串?

1 is the same amount as 1.00

So why do I need those zeros? 那么,为什么我需要那些零? Because an API I am working with expects float only. 因为我正在使用的API期望仅浮动。 Event 1 has to be passed as 1.00 float. 必须以1.00浮点形式传递事件1。 Any ideas? 有任何想法吗?

When returning the arguments just convert them to floats from string using parseFloat() on the string you get. 返回参数时,只需使用parseFloat()对所获取的字符串将其转换为浮点数即可。 Formatting is not part of the float type and thus only the value is stored. 格式化不是浮点类型的一部分,因此仅存储该值。 If you need formatting as well as the value, a custom class should be created. 如果需要格式和值,则应创建一个自定义类。

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

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