javascript格式的数字有2位数字

javascript格式的数字有2位数字

本文介绍了javascript格式的数字有2位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化一个数字只有2个数字。这个问题是由于0-9被传递的,所以我需要把它格式化为00-09?



在javascript中有一个数字格式化程序吗?



谢谢 解决方案

我找到的最佳方法如下所示请注意,这个简单的版本只适用于正整数):

var myNumber = 7; var formattedNumber =(0+ myNumber).slice(-2); console.log(formattedNumber);

p>

对于小数,你可以使用这个代码(虽然有点草率)。 data-lang =jsdata-hide =falsedata-console =truedata-babel =false>

  var myNumber = 7.5; var dec = myNumber  -  Math .floor(myNumber); myNumber = myNumber  -  dec; var formattedNumber =(0+ myNumber).slice(-2)+ dec.toString()。substr(1); console.log(formattedNumber);  

?-1:1:0; myNumber = myNumber * sign +''; //穷人的绝对值var dec = myNumber.match(/\.\d+ $ /); var int = myNumber.match(/ ^ [^ \。] + /); var formattedNumber =(sign


I want to format a number to have only 2 digits. The problem is caused when 0-9 is passed, so I need it to be formatted to 00-09?

Is there a number formatter in javascript?

Thanks

解决方案

The best method I've found is something like the following (Note that this simple version only works for positive integers):

var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);

For decimals, you could use this code (it's a bit sloppy though).

var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);

Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here: Number.sign() in javascript)

var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);

var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);

这篇关于javascript格式的数字有2位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:13