Skip to content

Instantly share code, notes, and snippets.

@nyawach
Created June 13, 2018 11:41
Show Gist options
  • Save nyawach/ae7c393c676efeb5a5668351a9b4cba7 to your computer and use it in GitHub Desktop.
Save nyawach/ae7c393c676efeb5a5668351a9b4cba7 to your computer and use it in GitHub Desktop.
n桁(+少数第m位)になおしてゼロパディングもする
import _ from "lodash"
/**
* 1000.234 => 0010,000.234
* @param val 元の値
* @param payload
* @param keta ゼロ字詰する桁数
* @param fixed 小数点以下の表示桁数
*/
export default (val, { keta = 0, fixed = 0 } = {}) => {
const fixedVal = val.toFixed(fixed)
const regex = /(\..+)$/
const after = regex.test(fixedVal) ? fixedVal.match(regex)[1] : ""
const padRevVal = _(parseInt(val, 10))
.padStart(keta, "0")
.split("")
.reverse()
.join("")
const before = _.reduce(padRevVal, (result, n) => {
if ((result.length - _.sumBy(result, v => v === ",")) % 3 === 0)
result = `,${result}`
return n + result
})
return before + after
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment