フォーマット数で二つの部で"年"、小数部で"JavaScript
-
19-09-2019 - |
質問
私はこのコードを選番号普ます。私番号のようになります:10.8,2.4等これらは私が考える場なのであまりにも改善は次のうちどれでしょう?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
したい番号のような10.80円減少,2.40。利用jQueryが進みください。
解決
固定点表記を使用して番号をフォーマットするには、単に使用できます トフィックス 方法:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
ご了承ください toFixed()
文字列を返します。
重要: :Tofixedは実際には90%の時間ではなく、丸い値を返しますが、多くの場合、実際には機能しません。コンソールでこれを試してください:
2.005.toFixed(2)
あなたは間違った答えを得るでしょう
JavaScriptで小数点以下の丸めを取得する自然な方法はありません。独自のポリフィルやライブラリを使用する必要があります。これについては、Mozillaのポリフィルを見ることができます https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/math/round
他のヒント
これは古いトピックですが、それでもトップランクの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ソリューションも使用し、10進数に合わせて適応可能にします。
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);
}
報告された例外のために機能します。
なぜ以前の答えにコメントを追加できないのかわかりません(多分私は絶望的に盲目です、Dunno)が、 @Miguelの答えを使用して解決策を思いつきました。
function precise_round(num,decimals) {
return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}
その2つのコメント(@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
小数値の右側。したがって、安全に使用する必要があります。
その後、私は追加しました .toFixed(decimal)
常に正しい形式で数値を出力するには(適切な量の小数を使用)。
だからそれはほとんどそれです。よく使う;)
編集:負の数の「修正」に機能を追加しました。
2つの小数の数字を取得することを100%確信する1つの方法:
(Math.round(num*100)/100).toFixed(2)
これが丸めエラーを引き起こす場合、ジェームズが彼のコメントで説明したように、次のことを使用できます。
(Math.round((num * 1000)/10)/100).toFixed(2)
Tofixed(n)は、小数点の後にnの長さを提供します。 procrecision(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
@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
});
});
デモをオンライン:
これが簡単なものです
function roundFloat(num,dec){
var d = 1;
for (var i=0; i<dec; i++){
d += "0";
}
return Math.round(num * d) / d;
}
のように使用します alert(roundFloat(1.79209243929,4));
浮動小数点値の問題は、固定量のビットで無限の(連続)値を表しようとしていることです。そのため、当然のことながら、プレイにいくらかの損失があるに違いありません。あなたはいくつかの価値に噛まれるでしょう。
コンピューターが1.275を浮動小数点値として保存する場合、1.275または1.274999999999993、さらには1.275500000000000000002であったかどうかは実際には覚えていません。これらの値は、2つの小数に丸めた後に異なる結果を与えるはずですが、コンピューターでは見た目があるので、そうしません。 まったく同じ 浮動小数点値として保存した後、失われたデータを復元する方法はありません。さらなる計算は、そのような不正確さのみを蓄積します。
したがって、精度が重要な場合は、最初から浮動小数点値を避けなければなりません。最も簡単なオプションは次のとおりです
- 使う 献身的なライブラリ
- 値を保存して渡すために文字列を使用します(文字列操作を伴う)
- 整数を使用します(たとえば、実際の価値の100分の1、たとえば、金額ではなくセントの金額を渡すことができます)
たとえば、整数を使用して100分の1を保存する場合、実際の値を見つける機能は非常に簡単です。
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 最寄りに丸くすることをお勧めします、 偶数と結びついています フローティングポイント操作のデフォルトの動作として。このような変更は、読者のための演習として残されています:)
小数値を回して、使用します toFixed(x)
予想される数字用。
function parseDecimalRoundAndFixed(num,dec){
var d = Math.pow(10,dec);
return (Math.round(num * d) / d).toFixed(dec);
}
電話
parsedecimalrownandfixed(10.800243929,4)=> 10.80 parsedecimalrowndandfixed(10.807243929,2)=> 10.81
/**
* MidpointRounding away from zero ('arithmetic' rounding)
* Uses a half-epsilon for correction. (This offsets IEEE-754
* half-to-even rounding that was applied at the edge cases).
*/
function RoundCorrect(num, precision = 2) {
// half epsilon to correct edge cases.
var c = 0.5 * Number.EPSILON * num;
// var p = Math.pow(10, precision); //slow
var p = 1; while (precision--> 0) p *= 10;
if (num < 0)
p *= -1;
return Math.round((num + c) * p) / p;
}
// testing some +ve edge cases
console.log(RoundCorrect(1.005, 2)); // 1.01 correct
console.log(RoundCorrect(2.175, 2)); // 2.18 correct
console.log(RoundCorrect(5.015, 2)); // 5.02 correct
// testing some -ve edge cases
console.log(RoundCorrect(-1.005, 2)); // -1.01 correct
console.log(RoundCorrect(-2.175, 2)); // -2.18 correct
console.log(RoundCorrect(-5.015, 2)); // -5.02 correct
これが私の1行の解決策です: Number((yourNumericValueHere).toFixed(2));
これが起こることです:
1)まず、適用します .toFixed(2)
小数点以下の場所を丸くしたい番号に。これにより、値が番号から文字列に変換されることに注意してください。したがって、TypeScriptを使用している場合、次のようなエラーが発生します。
「タイプ「文字列」は「番号」と入力することはできません」
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倍に2つの小数点に戻ります。
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
これは私のために働いた: JavaScriptの丸め小数
参照によりこの応答を使用してください: 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;
}
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>
丸くダウンします
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 ありがとう。
これらの例を使用すると、番号1.005を丸めようとすると、Math.jsのようなライブラリまたはこの関数を使用することです。
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
この投稿から数ヶ月前にいくつかのアイデアがありましたが、ここでの答えはありません。他の投稿/ブログからの回答は、すべてのシナリオを処理することもできません(マイナス数やテスターの「ラッキー数」が見つかったいくつかの「ラッキー数」)。最終的に、私たちのテスターは、以下のこの方法に問題は見つかりませんでした。私のコードのスニペットを貼り付けます:
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).
私は問題を修正装置に修正します。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>
(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
等
/*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;
私にとってこの問題を解決し、使用または適応させることができる非常に簡単な方法を見つけました。
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>