Last active
February 11, 2016 03:39
-
-
Save shuuuuun/6f31122ccee908ac87fd to your computer and use it in GitHub Desktop.
小数をdecimalLengthで切り捨てor四捨五入して、数値をカンマ区切りにするformatNumber関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatNumber(number, decimalLength) { | |
// 小数をdecimalLengthで切り捨てて、数値をカンマ区切りにする | |
decimalLength = decimalLength || 0; | |
var str = number.toString().split("."); | |
var base = str[0].replace(/(?!^)(?=(\d{3})+$)/g,","); | |
var decimal = (str[1]) ? str[1].slice(0, decimalLength) : Array(decimalLength + 1).join("0"); | |
var result = (!decimalLength) ? base : base + "." + decimal; | |
return result; | |
} | |
// ex. ----- | |
formatNumber(12345); // => "12,345" | |
formatNumber(12345.6789, 2); // => "12,345.67" | |
formatNumber(12345.6789, 3); // => "12,345.678" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatNumber(number, decimalLength) { | |
// 小数をdecimalLengthに四捨五入して、数値をカンマ区切りにする | |
decimalLength = decimalLength || 0; | |
var dimension = Math.pow(10, decimalLength); | |
var roundNum = Math.round(number * dimension) / dimension; | |
if (number < 0) roundNum *= -1; | |
var str = roundNum.toString().split("."); | |
var base = str[0].replace(/(?!^)(?=(\d{3})+$)/g,","); | |
var decimal = ((str[1] || "") + Array(decimalLength + 1).join("0")).slice(0, decimalLength); | |
var result = (!decimalLength) ? base : base + "." + decimal; | |
if (number < 0) result = "-" + result; | |
return result; | |
} | |
// ex. ----- | |
formatNumber(12345); // => "12,345" | |
formatNumber(12345.6789, 2); // => "12,345.68" | |
formatNumber(12345.6789, 3); // => "12,345.679" | |
formatNumber(12345.6999, 3); // => "12,345.700" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment