Javascript :将数字转换为十进制或添加零的多种方法介绍

123 阅读1分钟

在这篇博客中,我们将讨论在给定的数字或字符串中添加两个零的几种方法。
例如,我们有一个数字=12,我们必须在这个数字上加两个零来输出12.OO 在javascript中,数字值是以数字类型表示的。这个数字可以是12,-12,12.00。整数(12,-12)和浮点数(12.00)之间没有区别。数字也可以以strings("12")的形式存储
使用toFixed(2)方法转换为小数
Number.toFixed()方法用于格式化给定的数字,输出浮点数。以下是语法说明

  
Number.toFixed(decimalplacescount)  

这个方法只接受给定数字的decimalplacescount作为输入,返回小数点(.)后的数字数
在下面的例子中,给定的数字被转换为2位数的小数,如果输入的是字符串,会抛出**TypeError:strValue.toFixed不是一个函数,**使用parseInt将字符串转换为数字,并使用toFixed方法

let value=12;  
console.log(typeof value); //number  
  
console.log(value.toFixed(2)); //12.00  
  
let strValue="34";  
console.log(typeof strValue); //string  
console.log(strValue.toFixed(2)); //TypeError:strValue.toFixed is not a function  
  
let num=Number.parseInt(strValue)  
console.log(num.toFixed(2)); 

使用toLocaleString()方法转换为十位数

Number中的toLocaleString()方法用于给定数字的本地化版本。

toLocaleString(Locales,optionalConfigurations)  

locale是en或ES,
可选的配置是minimumFractionDigits =2,这是为了增加小数点后的数字
它接受英语语言。

var value = 17;      
var decimalNumber = value.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});  
console.log(decimalNumber);