JavaScriptで数値の3桁区切り表示方法

このQ&Aのポイント
  • JavaScriptで数値の3桁区切り表示方法を教えてください。
  • 質問者は数値を取得して消費税計算をし、四捨五入して、最後に3桁区切りのカンマを付けて表示したいと考えています。
  • 質問者はカンマの付け方が分からず困っています。助けてください。
回答を見る
  • ベストアンサー

javascriptで数値を3桁区切りで表示

数値を取得して消費税計算をして四捨五入して、あとは3桁区切りでカンマを付けて戻すだけなのですが、カンマの付け方がわかりません。 よろしくお願いします。 <script type="text/javascript"> var tax = 1.05; var targetClass='.price'; $(function() { $(targetClass).each(function(){ var price_a = $(this).text(); var price_b = price_a.replace(/,/g, ""); var price_c = price_b * tax; var price_d = Math.round(price_c); //切り上げ var price_d = Math.ceil(price_c); //切り捨て var price_d = Math.floor(price_c); $(this).text(price_d); }); }); </script> <p class="price">1,000</p> <p class="price">1,250</p> <p class="price">1,360</p> <p class="price">1,450</p> <p class="price">1,550</p> <p class="price">1,600</p>

質問者が選んだベストアンサー

  • ベストアンサー
  • Ogre7077
  • ベストアンサー率65% (170/258)
回答No.3

> エラーが出てしまう price_d を文字列にしましょう。 var price_d = Math.round(price_c).toString(); または var price_d = "" + Math.round(price_c); > 「var ○○○」がずらっと並んでいる そもそも計算途中の変数に "price_" は余分だと思いますので削除するとすっきりします var a = $(this).text(); var b = parseInt( a.replace(/,/g, "") ); // 安全のために parseInt は必要でしょう var c = b * tax; var d = Math.round(c).toString(); さらに変数定義はカンマ区切りで列挙できますので var a = $(this).text(), b = parseInt( a.replace(/,/g, "") ), c = b * tax, d = Math.round(c).toString(); そもそも計算途中の変数など不要だと思うなら var d = $(this).text(); d = parseInt( a.replace(/,/g, "") ); d *= tax; d = Math.round(d).toString(); 伝統芸である One-liner/一行野郎 の作法に従うなら 参考) http://en.wikipedia.org/wiki/One-liner_program var d = Math.round(parseInt($(this).text().replace(/,/g, "")) * tax).toString(); ですが結局はずらずら書くのが、一番安全で間違いのない記述ではないでしょうか。

Java-Java
質問者

お礼

ありがとうございました。 色々な記述方法があるんですね…、非常に参考になりました!

その他の回答 (3)

  • b0a0a
  • ベストアンサー率49% (156/313)
回答No.4

>もう少し簡略化して記述する方法はないでしょうか ある程度意味的にまとめてください それから途中のあまり重要でない変数の名前は思いつかなければ numやstrなど適当でもいいと思います var input = $(this).text(); //読み込み var num = +input.replace(/,/g, ""); //テキスト文字を数値に直す var price = Math.floor(num * tax); //税込み価格を出す var output = price.toLocaleString() //3桁区切りにする $(this).text(output); //書き込み もしくは正規化やパースの部分、入力出力の部分はもっとまとめてもいいと思います var zeinuki = +$(this).text().replace(/,/g, ""); //税抜き価格を取得 var zeikomi = Math.floor(zeinuki * tax); //税込みにする $(this).text(zeikomi.toLocaleString()); //税込み価格を出力

Java-Java
質問者

お礼

ありがとうございました。 意味的にまとめるといいのですね、参考になりました!

  • Ogre7077
  • ベストアンサー率65% (170/258)
回答No.2

文字列にして正規表現よる置換が一番確実でしょう "1234567890".replace(/(\d)(?=(\d{3})+$)/g, "$1,")

Java-Java
質問者

補足

ありがとうございます。 下記にしてやるとエラーが出てしまうのですが、どうしたらいいでしょうか。 ご教授下さい。 var price_e = price_d.replace(/(\d)(?=(\d{3})+$)/g, "$1,")

  • b0a0a
  • ベストアンサー率49% (156/313)
回答No.1

モダンブラウザであればNumber.prototype.toLocaleStringでできます n = 12345 n.toLocaleString() // "12,345"

Java-Java
質問者

お礼

ありがとうございます。うまくいきました。 もう一つ質問があるのですが、現在「var ○○○」がずらっと並んでいるのですが、これをもう少し簡略化して記述する方法はないでしょうか。 よろしくお願いします。

関連するQ&A

  • 金額表示で3桁ごとにカンマを付ける方法

    こんにちは。 JavaScriptで金額を表示する際にカンマ(,)を付けたいのですがうまくできません。 「値段は10,800円(税込)です。」と表示させたいのです。 toLocaleString関数を使用すればいいらしいですが、どのように記述すればいいのかわかりませんでした。 ご教示頂けませんか。 宜しくお願い致します。 <section> <p id="output"></p> </section> <script> var total = function(price) { var tax = 0.08; return price + price * tax; } document.getElementById('output').textContent = '値段は' + total(10000) + '円(税込)です。'; </script>

  • Javascript 計算後の3桁区切り

    ホームページ用見積もりフォームをJavascriptで自動計算 縦に長いページで一番下に計算結果を表示 ページをスクロールしても、何時でも計算結果が見られるように、別のウィンドウ(レイヤー)でページ内に表示。 以上までは出来ました。 最後に計算結果を3桁区切りで表示させたいのですが、上手く出来ません。 お知恵をお貸しくださいませ。 Javascriptは外部参照しております。 3桁区切りのJavascriptを外部参照している同一のページに記入した方が良いか、別参照の方が良いかも教えていただければ幸いです。 以下がJavascriptのコードになります。 function keisan(){ // 設定開始 var tax = 5; // 消費税率 // 商品1 var price1 = document.form1.goods1.options[document.form1.goods1.selectedIndex].value; // 商品2 var price2 = document.form1.goods2.options[document.form1.goods2.selectedIndex].value; // 商品3 var price3 = document.form1.goods3.options[document.form1.goods3.selectedIndex].value; // 合計を計算 var total1 = parseInt(price1) + parseInt(price2) + parseInt(price3) ; // 設定終了 document.form1.field_total1.value = total1; // 合計を表示 var tax2 = Math.round((total1 * tax) / 100); document.form1.field_tax.value = tax2; // 消費税を表示 document.form1.field_total2.value = total1 + tax2; // 税込合計を表示 //右の窓に表示する金額 document.getElementById("display_account_amount").innerHTML = total1; document.getElementById("display_account_tax").innerHTML = tax2; document.getElementById("display_account_all").innerHTML = total1 + tax2; }

  • javascriptカウントダウン終了後別ページへ

    javascriptでカウントダウン終了後に別ページに飛ばすリンクを表示したいのですが、どのようにすれば教えていただけますでしょうか? 下記スクリプトではカウントダウン終了時に「終了しました」と表示されます。 その「終了しました」にリンクを貼りたいです。 <script language="JavaScript" type="text/javascript"> function CountdownTimer(elm,tl,mes){ this.initialize.apply(this,arguments); } CountdownTimer.prototype={ initialize:function(elm,tl,mes) { this.elem = document.getElementById(elm); this.tl = tl; this.mes = mes; },countDown:function(){ var timer=''; var today=new Date(); var day=Math.floor((this.tl-today)/(24*60*60*1000)); var hour=Math.floor(((this.tl-today)%(24*60*60*1000))/(60*60*1000)); var min=Math.floor(((this.tl-today)%(24*60*60*1000))/(60*1000))%60; var sec=Math.floor(((this.tl-today)%(24*60*60*1000))/1000)%60%60; var milli=Math.floor(((this.tl-today)%(24*60*60*1000))/10)%100; var me=this; if( ( this.tl - today ) > 0 ){ if (day) timer += '<span class="day">'+day+':</span>'; if (hour) timer += '<span class="hour">'+hour+':</span>'; timer += '<span class="min">'+this.addZero(min)+':</span><span class="sec">'+this.addZero(sec)+':</span><span class="milli">'+this.addZero(milli)+'</span>'; this.elem.innerHTML = timer; tid = setTimeout( function(){me.countDown();},10 ); }else{ this.elem.innerHTML = this.mes; return; } },addZero:function(num){ return ('0'+num).slice(-2); } } function CDT(){ var tl = new Date('2013/2/1 00:00:00'); var timer = new CountdownTimer('CDT',tl,'終了しました'); timer.countDown(); } window.onload=function(){ CDT(); } </script>

  • javascriptについて教えてください。

    divのボタンを作りたいと思い、調べながらjQueryを使う方法は以下のようにしたらいい事は分かったのですが、jQueryを使わずにしようと思い $(function(){ $("div").click(function(){ var x = this.id; alert(x); }); }); の部分を document.getElementsByTagName("div").onclick = function(){ var x = this.id;  alert(x); }; としてみたのですが、うまくいきません。jQueryを使わずに同じようなボタンを作るにはどうしたらいいのでしょうか? <!doctype html> <html> <head> <meta charset="UTF-8"> <title>無題ドキュメント</title> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script> <script type="text/javascript" language="javascript"> $(function(){ $("div").click(function(){ var x = this.id; alert(x); }); }); </script> </head> <body> <div id="aaa" class="div_link">a</div> <div id="bbb" class="div_link">b</div> <div id="ccc" class="div_link">c</div> <div id="ddd" class="div_link">d</div> <div id="eee" class="div_link">e</div> </body> </html>

  • JavaScriptエラーが出ます…

    2つのJavaScriptエラーが出て大変困っております。 どなたか分かる方いらっしゃいませんでしょうか? ※当方はJavaScriptは分かりません。 検索にて調査いたしましたが、情けないですがもうお手上げ状態です。 ▼1つめ----------------------------------------------▼ メッセージ: 'null' は Null またはオブジェクトではありません。 ライン: 8 文字: 3 コード: 0 コード内容 以下 var accordion=function(){ var tm=10; var sp=10; function slider(n){ this.nm=n; this.arr=[]; this.sel='' } slider.prototype.init=function(t,c,k){ var a,h,s,l,i; a=document.getElementById(t); h=a.getElementsByTagName('dt'); s=a.getElementsByTagName('dd'); l=h.length; for(i=0;i<l;i++){ var d=h[i]; this.arr[i]=d; d.onclick=new Function(this.nm+".process(this)"); if(k!=null&&c==i){this.sel=d.className=k} } l=s.length; for(i=0;i<l;i++){ var d=s[i]; d.maxh=d.offsetHeight; if(c!=i){d.style.height='0'; d.style.display='none'} } } slider.prototype.process=function(d){ var i,l; l=this.arr.length; for(i=0;i<l;i++){ var h=this.arr[i]; var s=h.nextSibling; if(s.nodeType!=1){s=s.nextSibling} clearInterval(s.timer); if(h==d&&s.style.display=='none'){ s.style.display=''; setup(s,1); h.className=this.sel} else if(s.style.display==''){setup(s,-1); h.className=''} } } function setup(c,f){c.timer=setInterval(function(){slide(c,f)},tm)} function slide(c,f){ var h,m,d; h=c.offsetHeight; m=c.maxh; d=(f==1)?Math.ceil((m-h)/sp):Math.ceil(h/sp); c.style.height=h+(d*f)+'px'; c.style.opacity=h/m; c.style.filter='alpha(opacity='+h*100/m+')'; if(f==1&&h>=m){clearInterval(c.timer)} else if(f!=1&&h==1){c.style.display='none'; clearInterval(c.timer)} } return{slider:slider} }(); ▲1つめここまで----------------------------------------------▲ ▼2つめ----------------------------------------------▼ メッセージ: 'obj.length' は Null またはオブジェクトではありません。 ライン: 238 文字: 10 コード: 0 コード内容 以下 http://www.myulond.com/js.txt ▲1つめここまで----------------------------------------------▲ どうぞ、ご教授よろしくお願いいたします。

  • javascriptの計算フォームでカンマ区切り

    下記のようなjavascriptの計算フォームで計算結果に3ケタのカンマ区切りと小数点第2位までで切り捨てるようにしたいのですがどのようにすればよろしいでしょうか? 「javascript カンマ区切り」で検索したサイトをいろいろ見てみたのですが全然わかりません。 どなたかご教授お願い致します。 <head> <script language="JavaScript" type="text/JavaScript"> <!-- function Multiplication(form){ var test = form.ans.value = eval(form.num1.value)*eval(form.num2.value); return false; } --> </script> </head> <p>A×B×C=合計</p> <div> <form name="multiplication"> <input type="text" size="6" name="num1"> × <input type="text" size="6" name="num2" onBlur="Multiplication(this.form)"> = <input type="text" size="15" name="ans" class="txtbox">円(税別価格) <input type="reset" value="やり直し"> </form> </div> </body> </html>

  • 3桁区切り

    ドリームウィーバーで下記のJAVAスクリプトを挿入ました。 <!-- a = 10000; // b = 5000; //   d = a + b; // document.writeln(d); // // --> dの値を,(カンマ)で3桁区切りにする場合どのようにすればよいのでしょうか? 丸一日調べても、フォームを使用した物の記述しか見つからずに 困っています。

  • Javascript 足し算

    ホームページ用見積もりフォーム 商品の値段を合計する。 一個ずつ足しての計算で処理してるのですが、商品がかなりの数になりそうです。 エクセルのSUMのように商品1から商品1000までを計算する関数を教えていただきたいと思っています。 JavaScriptは外部参照しています。 以下がJavaScriptのコードになります。 function keisan(){ // 設定開始 var tax = 5; // 消費税率 // 商品1 var price1 = document.form1.goods1.options[document.form1.goods1.selectedIndex].value; // 商品2 var price2 = document.form1.goods2.options[document.form1.goods2.selectedIndex].value; // 商品3 var price3 = document.form1.goods3.options[document.form1.goods3.selectedIndex].value; // 合計を計算 var total1 = parseInt(price1) + parseInt(price2) + parseInt(price3); // 設定終了 document.form1.field_total1.value = editNumberSeparated(total1); // 合計を表示 var tax2 = Math.round((total1 * tax) / 100); document.form1.field_tax.value = editNumberSeparated(tax2); // 消費税を表示 document.form1.field_total2.value = editNumberSeparated(total1 + tax2); // 税込合計を表示

  • IE8で動作が遅くなるjavascriptメニュー

    いつもお世話になります。サイト製作初心者peace193と申します。 サンプルサイトを参考にjavascript+cssのグローバルメニュー、ローカルメニューを作ってみたのですが、IE7では快適に動く一方、IE8では動作が遅くなってしまいます。原因がわからずこちらに質問した次第です。 テストサーバに該当ページをUP致しました。お忙しい中恐縮ですが、ご教示のほど、なにとぞよろしくお願い申し上げます。 http://doa.nts21.jp/test001.html http://doa.nts21.jp/test002.html 参考サイトURL グローバルメニュー http://www.leigeber.com/2008/11/drop-down-menu/ ローカルメニュー http://roshanbh.com.np/2008/06/accordion-menu-using-jquery.html グローバルメニューjavascript var menu=function(){ var t=15,z=50,s=6,a; function dd(n){this.n=n; this.h=[]; this.c=[]} dd.prototype.init=function(p,c){ a=c; var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0; for(i;i<l;i++){ var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i]; h.onmouseover=new Function(this.n+'.st('+i+',true)'); h.onmouseout=new Function(this.n+'.st('+i+')'); } } dd.prototype.st=function(x,f){ var c=this.c[x], h=this.h[x], p=h.getElementsByTagName('a')[0]; clearInterval(c.t); c.style.overflow='hidden'; if(f){ p.className+=' '+a+x; if(!c.mh){c.style.display='block'; c.style.height=''; c.mh=c.offsetHeight; c.style.height=0} if(c.mh==c.offsetHeight){c.style.overflow='visible'} else{c.style.zIndex=z; z++; c.t=setInterval(function(){sl(c,1)},t)} }else{p.className=p.className.replace(a+x,''); c.t=setInterval(function(){sl(c,-1)},t)} } function sl(c,f){ var h=c.offsetHeight; if((h<=0&&f!=1)||(h>=c.mh&&f==1)){ if(f==1){c.style.filter=''; c.style.opacity=1; c.style.overflow='visible'} clearInterval(c.t); return } var d=(f==1)?Math.ceil((c.mh-h)/s):Math.ceil(h/s), o=h/c.mh; c.style.opacity=o; c.style.filter='alpha(opacity='+(o*100)+')'; c.style.height=h+(d*f)+'px' } return{dd:dd} }();

  • JavaScriptの画面表示について

    ●質問の主旨 次の文章の内容をGoogleChrome上で 表記したいのですが、 5行目の 「30個ご購入なら、通常72000円のところが、今なら48900円!」 が表記されません。 以下に示すコードのうちどこに問題があるでしょうか? ご存知のかたご教示よろしくお願いします。 ●本来表記したい文章 新製品 テンデイパックS のご紹介 話題の テンデイパックS を通常価格 2400 円のところを 特別価格 1680 円でご提供! まとめ買いならさらにお得! 10個につき500円お引きします。 30個ご購入なら、通常72000円のところが、今なら48900円! ●JavaScriptのコード <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>10日で覚えるJavaScript</title> <script type="text/javascript"> //変数の定義 var prod_name = 'テンデイパックS'; var prod_price = 2400; </script> </head> <body> <h1>新製品 <script type="text/javascript">document.write(prod_name);</script> のご紹介</h1> <p>話題の <script type="text/javascript">document.write(prod_name);</script> を通常価格 <script type="text/javascript">document.write(prod_price);</script> 円のところを</p> <p>特別価格 <script type="text/javascript">document.write(prod_price*0.7);</script> 円でご提供!</p> <p>まとめ買いならさらにお得!10個につき500円をお値引きいたします。</p> <script type="text/javascript"> var kosuu = 30; var special_price = prod_price * 0.7 * kosuu - kosuu / 10 * 500; document.write('<p>' + kosuu + '個ご購入なら、通常' + (prod_price * kosuu) + '円のところが、今なら' + special_price + '円!'</p>; </script> </body> </html>

専門家に質問してみよう