简体   繁体   English

将字符串转换为数字但在 Javascript 中保留零

[英]Convert string to number but maintain zeros in Javascript

I am working with GBP currency in Javascript and converting a string currency to a number like the following: Number('1.20') will give me 1.2 .我在 Javascript 中使用英镑货币并将字符串货币转换为如下数字: Number('1.20')将给我1.2 But I want to maintain the 0 when converting to a number type.但是我想在转换为number类型时保持0 Is this possible?这可能吗? This is the result that I want: 1.20 .这是我想要的结果: 1.20 Can anyone help me please?谁能帮帮我吗?

A better way to work with Currency in Javascript is to use the Intl.NumberFormat .在 Javascript 中使用货币的更好方法是使用Intl.NumberFormat For course, the output will be of the type: 'String'当然,output 的类型为:'String'

The output will take care of the number of decimal places depending on the Currency you specify. output 将根据您指定的货币处理小数位数。 In your case GBP so it will be 2 decimal places.在您的情况下, GBP将保留 2 位小数。

Example:例子:

 const number = 1.2; console.log(new Intl.NumberFormat('en', { style: 'currency', currency: 'GBP' }).format(number));

You can control the decimals like this in Javascript:在Javascript中可以这样控制小数:

let num = 1.204;
let n = num.toFixed(2)

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

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