{Number|String|BN} value
* @return {String}
*/
export function toMinimal (value, decimal) {
if (typeof decimal !== 'number') {
throw new TypeError('toMinimal error: decimal is not a number')
}
// hook for modify value like 1e-8
if (value.toString().indexOf('e') > 0) {
const valueParts = String(value).match(/^([\d.]+)e-?(\d+)$/)
value = `0.${new Array(parseInt(valueParts[2], 10)).join('0')}${valueParts[1].replace('.', '')}`
}
const [integerPart, fractionPart = ''] = value.toString().split(/[,.]/)
const paddedFraction = fractionPart.length < decimal
? fractionPart.padEnd(decimal, '0')
: fractionPart.substr(0, decimal)
const result = `${integerPart}${paddedFraction}`.replace(/^0+/, '')
if (result === '') {
return '0'
}
return result
}
/**
* To currency unit.
*
* @param {String|Number|BN} value
* @return {String}
*/
// eslint-disable-next-line no-shadow
export function toCurrency (value, decimal) {
if (typeof value === 'string') {
if (value.indexOf('.') !== -1) {
throw new Error(`${value} must not contain '.'`)
}
if (value.indexOf('-') !== -1) {
throw new Error(`${value} must not contain '-'`)
}
if (typeof decimal !== 'number') {
throw new TypeError('toCurrency error: decimal is not a number')
}
}
const valueBN = new BN(value)
if (valueBN.lte(0)) {
throw new Error('negative')
}
const valueString = new BN(value).toString()
const integerPart = valueString
.substring(0, valueString.length - decimal)
.replace(/^0+/, '') || 0
const fractionPart = valueString.substring(valueString.length - decimal)
.padStart(decimal, '0')
.replace(/0+$/, '')
if (fractionPart.search('-') !== -1) {
console.warn('convert: toCurrency: fractionPart is bad')
}
if (fractionPart !== '') {
return `${integerPart}.${fractionPart}`
}
return `${integerPart}`
}
Обсуждают сегодня