我有下面的代码。我想让它这样,如果price_result等于一个整数,比如10,然后我想加两位小数点后。所以10就是10.00。 如果等于10.6,就是10.60。不知道该怎么做。
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
我有下面的代码。我想让它这样,如果price_result等于一个整数,比如10,然后我想加两位小数点后。所以10就是10.00。 如果等于10.6,就是10.60。不知道该怎么做。
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
当前回答
如果你需要性能(游戏邦注:比如在游戏中):
Math.round(number * 100) / 100
它大约是parseFloat(number.toFixed(2))速度的100倍。
http://jsperf.com/parsefloat-tofixed-vs-math-round
其他回答
如果你的目标是解析,你的输入可能是一个文字,那么你会期望一个浮点数,而toFixed不会提供这个,所以这里有两个简单的函数来提供这个:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
您可以将价格存储为字符串
你可以使用 (字符串)
用于计算。
例子
Number("34.50") == 34.5
also
Number("35.65") == 35.65
如果你对数字函数感到舒服,你可以使用它。
如果你需要性能(游戏邦注:比如在游戏中):
Math.round(number * 100) / 100
它大约是parseFloat(number.toFixed(2))速度的100倍。
http://jsperf.com/parsefloat-tofixed-vs-math-round
Solution for FormArray controllers
初始化FormArray表单生成器
formInitilize() {
this.Form = this._formBuilder.group({
formArray: this._formBuilder.array([this.createForm()])
});
}
创建表单
createForm() {
return (this.Form = this._formBuilder.group({
convertodecimal: ['']
}));
}
将表单值设置为表单控制器
setFormvalues() {
this.Form.setControl('formArray', this._formBuilder.array([]));
const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
this.ListArrayValues.forEach((x) => {
control.push(this.buildForm(x));
});
}
private buildForm(x): FormGroup {
const bindvalues= this._formBuilder.group({
convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2) --- option for two decimal value
});
return bindvalues;
}
如果你不想四舍五入,请使用下面的函数。
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}