[英]Formatting a number with exactly two decimals in JavaScript
我有這行代碼將我的數字四舍五入到小數點后兩位。 但我得到這樣的數字:10.8、2.4 等。這些不是我對兩位小數的想法,所以我如何改進以下內容?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
我想要 10.80、2.40 等數字。我可以使用 jQuery。
要使用定點表示法格式化數字,您可以簡單地使用toFixed方法:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
請注意toFixed()
返回一個字符串。
重要提示:請注意,toFixed 在 90% 的情況下不會四舍五入,它將返回四舍五入的值,但在許多情況下,它不起作用。
例如:
2.005.toFixed(2) === "2.00"
現在,您可以使用Intl.NumberFormat
構造函數。 它是ECMAScript 國際化 API 規范(ECMA402) 的一部分。 它具有非常好的瀏覽器支持,甚至包括 IE11,並且在 Node.js 中完全支持。
const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formatter.format(2.005)); // "2.01" console.log(formatter.format(1.345)); // "1.35"
您也可以使用toLocaleString
方法,該方法在內部將使用Intl
API:
const format = (num, decimals) => num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(format(2.005)); // "2.01" console.log(format(1.345)); // "1.35"
此 API 還為您提供了多種格式化選項,例如千位分隔符、貨幣符號等。
這是一個古老的話題,但仍然是排名靠前的 Google 結果,並且提供的解決方案共享相同的浮點小數問題。 這是我使用的(非常通用的)函數, 感謝 MDN :
function round(value, exp) {
if (typeof exp === 'undefined' || +exp === 0)
return Math.round(value);
value = +value;
exp = +exp;
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}
正如我們所見,我們沒有遇到這些問題:
round(1.275, 2); // Returns 1.28
round(1.27499, 2); // Returns 1.27
這種通用性還提供了一些很酷的東西:
round(1234.5678, -2); // Returns 1200
round(1.2345678e+2, 2); // Returns 123.46
round("123.45"); // Returns 123
現在,要回答 OP 的問題,必須輸入:
round(10.8034, 2).toFixed(2); // Returns "10.80"
round(10.8, 2).toFixed(2); // Returns "10.80"
或者,對於更簡潔、更不通用的函數:
function round2Fixed(value) {
value = +value;
if (isNaN(value))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + 2) : 2)));
// Shift back
value = value.toString().split('e');
return (+(value[0] + 'e' + (value[1] ? (+value[1] - 2) : -2))).toFixed(2);
}
您可以通過以下方式調用它:
round2Fixed(10.8034); // Returns "10.80"
round2Fixed(10.8); // Returns "10.80"
各種示例和測試(感謝@tj-crowder !):
function round(value, exp) { if (typeof exp === 'undefined' || +exp === 0) return Math.round(value); value = +value; exp = +exp; if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) return NaN; // Shift value = value.toString().split('e'); value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp))); // Shift back value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)); } function naive(value, exp) { if (!exp) { return Math.round(value); } var pow = Math.pow(10, exp); return Math.round(value * pow) / pow; } function test(val, places) { subtest(val, places); val = typeof val === "string" ? "-" + val : -val; subtest(val, places); } function subtest(val, places) { var placesOrZero = places || 0; var naiveResult = naive(val, places); var roundResult = round(val, places); if (placesOrZero >= 0) { naiveResult = naiveResult.toFixed(placesOrZero); roundResult = roundResult.toFixed(placesOrZero); } else { naiveResult = naiveResult.toString(); roundResult = roundResult.toString(); } $("<tr>") .append($("<td>").text(JSON.stringify(val))) .append($("<td>").text(placesOrZero)) .append($("<td>").text(naiveResult)) .append($("<td>").text(roundResult)) .appendTo("#results"); } test(0.565, 2); test(0.575, 2); test(0.585, 2); test(1.275, 2); test(1.27499, 2); test(1234.5678, -2); test(1.2345678e+2, 2); test("123.45"); test(10.8034, 2); test(10.8, 2); test(1.005, 2); test(1.0005, 2);
table { border-collapse: collapse; } table, td, th { border: 1px solid #ddd; } td, th { padding: 4px; } th { font-weight: normal; font-family: sans-serif; } td { font-family: monospace; }
<table> <thead> <tr> <th>Input</th> <th>Places</th> <th>Naive</th> <th>Thorough</th> </tr> </thead> <tbody id="results"> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我通常將它添加到我的個人庫中,經過一些建議並使用@TIMINeutron 解決方案,然后使其適應十進制長度,這個最適合:
function precise_round(num, decimals) {
var t = Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
將適用於報告的異常。
我不知道為什么我不能在以前的答案中添加評論(也許我完全瞎了,我不知道),但我想出了一個使用@Miguel 的答案的解決方案:
function precise_round(num,decimals) {
return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}
以及它的兩條評論(來自@bighostkim 和@Imre):
precise_round(1.275,2)
不返回 1.28 的問題precise_round(6,2)
沒有返回 6.00 的問題(如他所願)。我的最終解決方案如下:
function precise_round(num,decimals) {
var sign = num >= 0 ? 1 : -1;
return (Math.round((num*Math.pow(10,decimals)) + (sign*0.001)) / Math.pow(10,decimals)).toFixed(decimals);
}
正如你所看到的,我不得不添加一點“更正”(它不是這樣,但因為 Math.round 是有損的——你可以在 jsfiddle.net 上檢查它——這是我知道如何“修復”的唯一方法”它)。 它將 0.001 添加到已經填充的數字上,因此它在十進制值的右側添加一個1
三0
s。 所以使用起來應該是安全的。
之后,我添加了.toFixed(decimal)
以始終以正確的格式輸出數字(具有正確的小數位數)。
差不多就是這樣。 好好利用它;)
編輯:為負數的“更正”添加了功能。
一種 100% 確定您得到一個帶有 2 個小數的數字的方法:
(Math.round(num*100)/100).toFixed(2)
如果這導致四舍五入錯誤,您可以使用以下內容,正如 James 在他的評論中所解釋的那樣:
(Math.round((num * 1000)/10)/100).toFixed(2)
toFixed(n) 提供小數點后的 n 個長度; toPrecision(x) 提供 x 總長度。
使用下面這個方法
// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
並且如果您希望號碼固定使用
result = num.toFixed(2);
我沒有找到這個問題的准確解決方案,所以我創建了自己的:
function inprecise_round(value, decPlaces) {
return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
}
function precise_round(value, decPlaces){
var val = value * Math.pow(10, decPlaces);
var fraction = (Math.round((val-parseInt(val))*10)/10);
//this line is for consistency with .NET Decimal.Round behavior
// -342.055 => -342.06
if(fraction == -0.5) fraction = -0.6;
val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
return val;
}
例子:
function inprecise_round(value, decPlaces) { return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces); } function precise_round(value, decPlaces) { var val = value * Math.pow(10, decPlaces); var fraction = (Math.round((val - parseInt(val)) * 10) / 10); //this line is for consistency with .NET Decimal.Round behavior // -342.055 => -342.06 if (fraction == -0.5) fraction = -0.6; val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces); return val; } // This may produce different results depending on the browser environment console.log("342.055.toFixed(2) :", 342.055.toFixed(2)); // 342.06 on Chrome & IE10 console.log("inprecise_round(342.055, 2):", inprecise_round(342.055, 2)); // 342.05 console.log("precise_round(342.055, 2) :", precise_round(342.055, 2)); // 342.06 console.log("precise_round(-342.055, 2) :", precise_round(-342.055, 2)); // -342.06 console.log("inprecise_round(0.565, 2) :", inprecise_round(0.565, 2)); // 0.56 console.log("precise_round(0.565, 2) :", precise_round(0.565, 2)); // 0.57
parseFloat(number.toFixed(2))
let number = 2.55435930
let roundedString = number.toFixed(2) // "2.55"
let twoDecimalsNumber = parseFloat(roundedString) // 2.55
let directly = parseFloat(number.toFixed(2)) // 2.55
@heridev 和我在 jQuery 中創建了一個小函數。
您可以嘗試下一個:
HTML
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
jQuery
// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this; //for chaining
});
});
在線演示:
浮點值的問題在於它們試圖用固定數量的位來表示無限數量的(連續)值。 所以很自然地,在比賽中肯定會有一些損失,你會被一些價值觀所困擾。
當計算機將 1.275 存儲為浮點值時,它實際上不會記住它是 1.275 還是 1.27499999999999993,甚至 1.27500000000000002。 這些值在四舍五入到兩位小數后應該給出不同的結果,但它們不會,因為對於計算機它們在存儲為浮點值后看起來完全相同,並且無法恢復丟失的數據。 任何進一步的計算只會累積這種不精確性。
因此,如果精度很重要,您必須從一開始就避免使用浮點值。 最簡單的選擇是
例如,當使用整數存儲百分數時,查找實際值的函數非常簡單:
function descale(num, decimals) {
var hasMinus = num < 0;
var numString = Math.abs(num).toString();
var precedingZeroes = '';
for (var i = numString.length; i <= decimals; i++) {
precedingZeroes += '0';
}
numString = precedingZeroes + numString;
return (hasMinus ? '-' : '')
+ numString.substr(0, numString.length-decimals)
+ '.'
+ numString.substr(numString.length-decimals);
}
alert(descale(127, 2));
對於字符串,您需要四舍五入,但它仍然可以管理:
function precise_round(num, decimals) {
var parts = num.split('.');
var hasMinus = parts.length > 0 && parts[0].length > 0 && parts[0].charAt(0) == '-';
var integralPart = parts.length == 0 ? '0' : (hasMinus ? parts[0].substr(1) : parts[0]);
var decimalPart = parts.length > 1 ? parts[1] : '';
if (decimalPart.length > decimals) {
var roundOffNumber = decimalPart.charAt(decimals);
decimalPart = decimalPart.substr(0, decimals);
if ('56789'.indexOf(roundOffNumber) > -1) {
var numbers = integralPart + decimalPart;
var i = numbers.length;
var trailingZeroes = '';
var justOneAndTrailingZeroes = true;
do {
i--;
var roundedNumber = '1234567890'.charAt(parseInt(numbers.charAt(i)));
if (roundedNumber === '0') {
trailingZeroes += '0';
} else {
numbers = numbers.substr(0, i) + roundedNumber + trailingZeroes;
justOneAndTrailingZeroes = false;
break;
}
} while (i > 0);
if (justOneAndTrailingZeroes) {
numbers = '1' + trailingZeroes;
}
integralPart = numbers.substr(0, numbers.length - decimals);
decimalPart = numbers.substr(numbers.length - decimals);
}
} else {
for (var i = decimalPart.length; i < decimals; i++) {
decimalPart += '0';
}
}
return (hasMinus ? '-' : '') + integralPart + (decimals > 0 ? '.' + decimalPart : '');
}
alert(precise_round('1.275', 2));
alert(precise_round('1.27499999999999993', 2));
請注意,此函數舍入到最接近,遠離零,而IEEE 754建議舍入到最接近,與 even作為浮點運算的默認行為。 此類修改留給讀者作為練習:)
這是一個簡單的
function roundFloat(num,dec){
var d = 1;
for (var i=0; i<dec; i++){
d += "0";
}
return Math.round(num * d) / d;
}
使用 like alert(roundFloat(1.79209243929,4));
向下舍入
function round_down(value, decPlaces) {
return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
向上舍入
function round_up(value, decPlaces) {
return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
圓形最近
function round_nearest(value, decPlaces) {
return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
合並https://stackoverflow.com/a/7641824/1889449和https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm謝謝他們。
四舍五入您的十進制值,然后使用toFixed(x)
作為您預期的數字。
function parseDecimalRoundAndFixed(num,dec){
var d = Math.pow(10,dec);
return (Math.round(num * d) / d).toFixed(dec);
}
稱呼
parseDecimalRoundAndFixed(10.800243929,4) => 10.80 parseDecimalRoundAndFixed(10.807243929,2) => 10.81
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
對於這些示例,您在嘗試對數字 1.005 進行四舍五入時仍會遇到錯誤,解決方案是使用像 Math.js 這樣的庫或此函數:
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
一般來說,小數四舍五入是通過縮放來完成的: round(num * p) / p
幼稚的實現
使用帶有中間數字的以下函數,您將獲得預期的上舍入值,或有時取決於輸入的舍入下值。
這種舍入inconsistency
可能會在客戶端代碼中引入難以檢測的錯誤。
function naiveRound(num, decimalPlaces) { var p = Math.pow(10, decimalPlaces); return Math.round(num * p) / p; } console.log( naiveRound(1.245, 2) ); // 1.25 correct (rounded as expected) console.log( naiveRound(1.255, 2) ); // 1.25 incorrect (should be 1.26)
更好的實現
通過將數字轉換為指數表示法中的字符串,正數將按預期四舍五入。 但是,請注意負數與正數的舍入方式不同。
事實上,它執行的規則基本上相當於“四舍五入” ,您會看到round(-1.005, 2)
計算結果為-1
即使round(1.005, 2)
計算結果為1.01
。 lodash _.round 方法使用這種技術。
/** * Round half up ('round half towards positive infinity') * Uses exponential notation to avoid floating-point issues. * Negative numbers round differently than positive numbers. */ function round(num, decimalPlaces) { num = Math.round(num + "e" + decimalPlaces); return Number(num + "e" + -decimalPlaces); } // test rounding of half console.log( round(0.5, 0) ); // 1 console.log( round(-0.5, 0) ); // 0 // testing edge cases console.log( round(1.005, 2) ); // 1.01 console.log( round(2.175, 2) ); // 2.18 console.log( round(5.015, 2) ); // 5.02 console.log( round(-1.005, 2) ); // -1 console.log( round(-2.175, 2) ); // -2.17 console.log( round(-5.015, 2) ); // -5.01
如果您在舍入負數時想要通常的行為,則需要在調用Math.round()之前將負數轉換為正數,然后在返回之前將它們轉換回負數。
// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}
有一種不同的純數學技術來執行舍入到最近(使用"round half away from zero" ),其中在調用舍入函數之前應用epsilon 校正。
簡單地說,我們在四舍五入之前將可能的最小浮點值(= 1.0 ulp;單位在最后一位)添加到數字中。 這將移動到數字之后的下一個可表示值,遠離零。
/** * Round half away from zero ('commercial' rounding) * Uses correction to offset floating-point inaccuracies. * Works symmetrically for positive and negative numbers. */ function round(num, decimalPlaces) { var p = Math.pow(10, decimalPlaces); var e = Number.EPSILON * num * p; return Math.round((num * p) + e) / p; } // test rounding of half console.log( round(0.5, 0) ); // 1 console.log( round(-0.5, 0) ); // -1 // testing edge cases console.log( round(1.005, 2) ); // 1.01 console.log( round(2.175, 2) ); // 2.18 console.log( round(5.015, 2) ); // 5.02 console.log( round(-1.005, 2) ); // -1.01 console.log( round(-2.175, 2) ); // -2.18 console.log( round(-5.015, 2) ); // -5.02
這需要抵消在十進制數編碼期間可能發生的隱式舍入誤差,特別是那些在最后一個小數位上有“5”的數字,如 1.005、2.675 和 16.235。 實際上,十進制的1.005
被編碼為 64 位二進制浮點數的1.0049999999999999
; 而十進制的1234567.005
被編碼為1234567.0049999998882413
的 64 位二進制浮點數。
值得注意的是,最大二進制round-off error
取決於 (1) 數字的大小和 (2) 相對機器 epsilon (2^-52)。
這是我的 1 行解決方案: Number((yourNumericValueHere).toFixed(2));
這是發生的事情:
1) 首先,將.toFixed(2)
到要舍入小數位的數字上。 請注意,這會將值從數字轉換為字符串。 所以如果你使用 Typescript,它會拋出這樣的錯誤:
“類型 'string' 不可分配給類型 'number'”
2) 要取回數值或將字符串轉換為數值,只需對所謂的“字符串”值應用Number()
函數。
為了澄清,請看下面的例子:
示例:我有一個小數位最多有 5 位數字的金額,我想將其縮短為最多 2 個小數位。 我這樣做:
var price = 0.26453; var priceRounded = Number((price).toFixed(2)); console.log('Original Price: ' + price); console.log('Price Rounded: ' + priceRounded);
將以下內容放在某個全局范圍內:
Number.prototype.getDecimals = function ( decDigCount ) {
return this.toFixed(decDigCount);
}
然后嘗試:
var a = 56.23232323;
a.getDecimals(2); // will return 56.23
請注意, toFixed()
只能適用於0-20
之間的小數位數,即a.getDecimals(25)
可能會生成 javascript 錯誤,因此為了適應您可以添加一些額外的檢查,即
Number.prototype.getDecimals = function ( decDigCount ) {
return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
Number(((Math.random() * 100) + 1).toFixed(2))
這將返回一個從 1 到 100 舍入到小數點后兩位的隨機數。
通過參考使用此響應: https : //stackoverflow.com/a/21029698/454827
我構建了一個函數來獲取動態小數位數:
function toDec(num, dec)
{
if(typeof dec=='undefined' || dec<0)
dec = 2;
var tmp = dec + 1;
for(var i=1; i<=tmp; i++)
num = num * 10;
num = num / 10;
num = Math.round(num);
for(var i=1; i<=dec; i++)
num = num / 10;
num = num.toFixed(dec);
return num;
}
這里的工作示例: https : //jsfiddle.net/wpxLduLc/
parse = function (data) { data = Math.round(data*Math.pow(10,2))/Math.pow(10,2); if (data != null) { var lastone = data.toString().split('').pop(); if (lastone != '.') { data = parseFloat(data); } } return data; }; $('#result').html(parse(200)); // output 200 $('#result1').html(parse(200.1)); // output 200.1 $('#result2').html(parse(200.10)); // output 200.1 $('#result3').html(parse(200.109)); // output 200.11
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="result"></div> <div id="result1"></div> <div id="result2"></div> <div id="result3"></div>
幾個月前我從這篇文章中得到了一些想法,但是這里的答案,以及其他文章/博客的答案都不能處理所有情況(例如,我們的測試人員發現的負數和一些“幸運數字”)。 最終我們的測試人員沒有發現下面這個方法有什么問題。 粘貼我的代碼片段:
fixPrecision: function (value) {
var me = this,
nan = isNaN(value),
precision = me.decimalPrecision;
if (nan || !value) {
return nan ? '' : value;
} else if (!me.allowDecimals || precision <= 0) {
precision = 0;
}
//[1]
//return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
precision = precision || 0;
var negMultiplier = value < 0 ? -1 : 1;
//[2]
var numWithExp = parseFloat(value + "e" + precision);
var roundedNum = parseFloat(Math.round(Math.abs(numWithExp)) + 'e-' + precision) * negMultiplier;
return parseFloat(roundedNum.toFixed(precision));
},
我也有代碼注釋(對不起,我已經忘記了所有細節)......我在這里發布我的答案以供將來參考:
9.995 * 100 = 999.4999999999999
Whereas 9.995e2 = 999.5
This discrepancy causes Math.round(9.995 * 100) = 999 instead of 1000.
Use e notation instead of multiplying /dividing by Math.Pow(10,precision).
(Math.round((10.2)*100)/100).toFixed(2)
那應該產生: 10.20
(Math.round((.05)*100)/100).toFixed(2)
那應該產生: 0.05
(Math.round((4.04)*100)/100).toFixed(2)
那應該產生: 4.04
等等。
我正在解決修改器的問題。 僅支持 2 位小數。
$(function(){ //input number only. convertNumberFloatZero(22); // output : 22.00 convertNumberFloatZero(22.5); // output : 22.50 convertNumberFloatZero(22.55); // output : 22.55 convertNumberFloatZero(22.556); // output : 22.56 convertNumberFloatZero(22.555); // output : 22.55 convertNumberFloatZero(22.5541); // output : 22.54 convertNumberFloatZero(22222.5541); // output : 22,222.54 function convertNumberFloatZero(number){ if(!$.isNumeric(number)){ return 'NaN'; } var numberFloat = number.toFixed(3); var splitNumber = numberFloat.split("."); var cNumberFloat = number.toFixed(2); var cNsplitNumber = cNumberFloat.split("."); var lastChar = splitNumber[1].substr(splitNumber[1].length - 1); if(lastChar > 0 && lastChar < 5){ cNsplitNumber[1]--; } return Number(splitNumber[0]).toLocaleString('en').concat('.').concat(cNsplitNumber[1]); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
/*Due to all told stuff. You may do 2 things for different purposes: When showing/printing stuff use this in your alert/innerHtml= contents: YourRebelNumber.toFixed(2)*/ var aNumber=9242.16; var YourRebelNumber=aNumber-9000; alert(YourRebelNumber); alert(YourRebelNumber.toFixed(2)); /*and when comparing use: Number(YourRebelNumber.toFixed(2))*/ if(YourRebelNumber==242.16)alert("Not Rounded"); if(Number(YourRebelNumber.toFixed(2))==242.16)alert("Rounded"); /*Number will behave as you want in that moment. After that, it'll return to its defiance. */
這非常簡單,並且與其他任何方法一樣有效:
function parseNumber(val, decimalPlaces) {
if (decimalPlaces == null) decimalPlaces = 0
var ret = Number(val).toFixed(decimalPlaces)
return Number(ret)
}
由於 toFixed() 只能在數字上調用,並且不幸的是返回一個字符串,因此它會為您完成雙向的所有解析。 您可以傳遞一個字符串或一個數字,並且每次都會返回一個數字! 調用 parseNumber(1.49) 會給你 1,而 parseNumber(1.49,2) 會給你 1.50。 就像他們中最好的一樣!
您還可以使用.toPrecision()
方法和一些自定義代碼,並且無論 int 部分的長度如何,始終向上舍入到第 n 個十進制數字。
function glbfrmt (number, decimals, seperator) {
return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}
您也可以將其作為插件以更好地使用。
就這么簡單。
var rounded_value=Math.round(value * 100) / 100;
這是https://stackoverflow.com/a/21323330/916734的 TypeScript 實現。 它還通過函數使事情變干,並允許可選的數字偏移量。
export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
const value = Number(rawValue);
if (isNaN(value)) return rawValue;
precision = Number(precision);
if (precision % 1 !== 0) return NaN;
let [ stringValue, exponent ] = scientificNotationToParts(value);
let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
const enlargedValue = toScientificNotation(stringValue, shiftExponent);
const roundedValue = Math.round(enlargedValue);
[ stringValue, exponent ] = scientificNotationToParts(roundedValue);
const precisionWithOffset = precision + fractionDigitOffset;
shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);
return toScientificNotation(stringValue, shiftExponent);
}
enum Shift {
Left = -1,
Right = 1,
}
function scientificNotationToParts(value: number): Array<string> {
const [ stringValue, exponent ] = value.toString().split('e');
return [ stringValue, exponent ];
}
function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
precision = shift * precision;
return exponent ? (Number(exponent) + precision) : precision;
}
function toScientificNotation(value: string, exponent: number): number {
return Number(`${value}e${exponent}`);
}
建立在Christian C. Salvadó 的回答之上,執行以下操作將輸出一個Number
類型,並且似乎也能很好地處理四舍五入:
const roundNumberToTwoDecimalPlaces = (num) => Number(new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(num));
roundNumberToTwoDecimalPlaces(1.344); // => 1.34
roundNumberToTwoDecimalPlaces(1.345); // => 1.35
上述內容與已經提到的內容之間的區別在於,您在使用它時不需要.format()
鏈接[,並且它輸出一個Number
類型]。
fun Any.twoDecimalPlaces(numInDouble: Double): String {
return "%.2f".format(numInDouble)
}
我找到了一個非常簡單的方法,為我解決了這個問題,可以使用或改編:
td[row].innerHTML = price.toPrecision(price.toFixed(decimals).length
100%工作!!! 試試吧
<html> <head> <script> function replacePonto(){ var input = document.getElementById('qtd'); var ponto = input.value.split('.').length; var slash = input.value.split('-').length; if (ponto > 2) input.value=input.value.substr(0,(input.value.length)-1); if(slash > 2) input.value=input.value.substr(0,(input.value.length)-1); input.value=input.value.replace(/[^0-9.-]/,''); if (ponto ==2) input.value=input.value.substr(0,(input.value.indexOf('.')+3)); if(input.value == '.') input.value = ""; } </script> </head> <body> <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()"> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.