coin-format
Advanced tools
Comparing version 0.0.1 to 0.0.2
declare const DEFAULT_DECIMALS = 18; | ||
declare const coinsToWeiInBigInt: (value: string | number, decimals?: number) => bigint; | ||
declare const coinsToWei: (value: string | number, decimals?: number) => string; | ||
declare const weiToCoins: (weiValue: string | bigint, decimals?: number) => string; | ||
declare const dangerouslyWeiToCoinsInFloat: (weiValue: string | bigint, decimals?: number) => number; | ||
declare const format: (value: string | number, formattingThreshold?: number) => string; | ||
declare const formatPrecise: (value: string | number, precision?: number) => string; | ||
declare const formatWithCurrency: (value: string | number, currency?: string, formattingThreshold?: number) => string; | ||
declare const weiFormat: (weiValue: string | bigint, decimals?: number, formattingThreshold?: number) => string; | ||
declare const weiFormatPrecise: (weiValue: string | bigint, precision?: number) => string; | ||
declare const coinToWeiInBigInt: (value: string | number, decimals?: number) => bigint; | ||
declare const coinToWei: (value: string | number, decimals?: number) => string; | ||
declare const weiToCoin: (weiValue: string | bigint, decimals?: number) => string; | ||
declare const dangerouslyWeiToCoinInFloat: (weiValue: string | bigint, decimals?: number) => number; | ||
declare const formatNice: (value: string | number, formattingThreshold?: number) => string; | ||
declare const formatFixed: (value: string | number, precision?: number) => string; | ||
declare const weiFormatNice: (weiValue: string | bigint, decimals?: number, formattingThreshold?: number) => string; | ||
declare const weiFormatFixed: (weiValue: string | bigint, decimals?: number, precision?: number) => string; | ||
declare const weiToGwei: (gwei: string | bigint, decimals?: number) => string; | ||
declare const gweiToWei: (gwei: string | number | bigint, decimals?: number) => string; | ||
declare const coinToGwei: (value: string | number, decimals?: number) => string; | ||
declare const gweiToCoin: (value: string | number, decimals?: number) => string; | ||
declare const cleanUpCoinsValue: (value: string | number) => string; | ||
declare const Coin: (currency: string, decimals?: number, precision?: number, formattingThreshold?: number) => { | ||
coinsToWeiInBigInt: (value: string) => bigint; | ||
coinsToWei: (value: string) => string; | ||
weiToCoins: (value: string | bigint) => string; | ||
dangerouslyWeiToCoinsInFloat: (value: string | bigint) => number; | ||
format: (value: string) => string; | ||
formatPrecise: (value: string | number, _precision?: number) => string; | ||
formatPure: (value: string | number) => string; | ||
formatPurePrecise: (value: string | number, _precision?: number) => string; | ||
weiFormat: (value: string | bigint) => string; | ||
weiFormatPrecise: (value: string | bigint, _precision?: number) => string; | ||
weiFormatPure: (value: string | bigint) => string; | ||
weiFormatPurePrecise: (value: string | bigint, _precision?: number) => string; | ||
coinToWeiInBigInt: (value: string) => bigint; | ||
coinToWei: (value: string) => string; | ||
weiToCoin: (value: string | bigint) => string; | ||
dangerouslyWeiToCoinInFloat: (value: string | bigint) => number; | ||
formatNice: (value: string) => string; | ||
formatMetric: (value: string) => string; | ||
formatFixed: (value: string | number, _precision?: number) => string; | ||
formatFixedClean: (value: string | number, _precision?: number) => string; | ||
weiFormatNice: (value: string | bigint) => string; | ||
weiFormatMetric: (value: string | bigint) => string; | ||
weiFormatFixed: (value: string | bigint, _precision?: number) => string; | ||
weiFormatFixedClean: (value: string | bigint, _precision?: number) => string; | ||
gwei: { | ||
gweiToWei: (value: string | number | bigint) => string; | ||
weiToGwei: (value: string | bigint) => string; | ||
gweiToCoin: (value: string | number) => string; | ||
coinToGwei: (value: string | number) => string; | ||
}; | ||
inAllFormats: (value: string | number, _precision?: number) => ICoinFormats; | ||
@@ -28,5 +38,6 @@ weiInAllFormats: (wei: string | bigint, _precision?: number) => ICoinFormats; | ||
type ICoinFormats = { | ||
parsed: string; | ||
full: string; | ||
precise: string; | ||
value: string; | ||
metric: string; | ||
nice: string; | ||
fixed: string; | ||
exact: string; | ||
@@ -38,2 +49,2 @@ currency: string; | ||
export { Coin, DEFAULT_DECIMALS, type ICoin, type ICoinFormats, coinsToWei, coinsToWeiInBigInt, dangerouslyWeiToCoinsInFloat, format, formatPrecise, formatWithCurrency, weiFormat, weiFormatPrecise, weiToCoins }; | ||
export { Coin, DEFAULT_DECIMALS, type ICoin, type ICoinFormats, cleanUpCoinsValue, coinToGwei, coinToWei, coinToWeiInBigInt, dangerouslyWeiToCoinInFloat, formatFixed, formatNice, gweiToCoin, gweiToWei, weiFormatFixed, weiFormatNice, weiToCoin, weiToGwei }; |
@@ -1,2 +0,2 @@ | ||
"use strict";var CoinFormat=(()=>{var p=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var x=(r,t)=>{for(var i in t)p(r,i,{get:t[i],enumerable:!0})},D=(r,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of P(t))!S.call(r,e)&&e!==i&&p(r,e,{get:()=>t[e],enumerable:!(s=A(t,e))||s.enumerable});return r};var $=r=>D(p({},"__esModule",{value:!0}),r);var _={};x(_,{Coin:()=>M,DEFAULT_DECIMALS:()=>L,coinsToWei:()=>I,coinsToWeiInBigInt:()=>E,dangerouslyWeiToCoinsInFloat:()=>F,format:()=>u,formatPrecise:()=>c,formatWithCurrency:()=>T,weiFormat:()=>l,weiFormatPrecise:()=>w,weiToCoins:()=>f});var L=18,d=r=>{if(typeof r!="number")throw new Error("Invalid decimals, must be a number");if(r<1||r>18)throw new Error("Invalid decimals, must be between 0 and 18");return!0},E=(r,t=18)=>{if(r=r.toString(),!/^\d+(\.\d+)?$/.test(r))throw new Error("Invalid value");d(t);let i=10n**BigInt(t),[s,e=""]=r.split(".");return e=e.padEnd(t,"0").slice(0,t),BigInt(s)*i+BigInt(e)},I=(r,t=18)=>E(r,t).toString(),f=(r,t=18)=>{d(t);let i=BigInt(r),s=10n**BigInt(t),e=i/s,g=(i%s).toString().padStart(t,"0").replace(/0+$/,"");return`${e}${g.length>0?"."+g:""}`},F=(r,t=18)=>parseFloat(f(r,t)),u=(r,t=1e5)=>{let i=typeof r=="string"?r:r.toString(),s=parseFloat(i);if(isNaN(s))throw new Error(`Coin.format: Invalid number: ${i}`);if(t===-1)return i;let[e,n=""]=i.split("."),o=parseInt(e);if(o<t){if(!n)return i;let C=parseFloat(`0.${n}`),a=0;C<.1?a=6:o<1?a=4:o<10?a=3:o<1e4?a=2:o<1e5&&(a=1);let b=n.substring(0,a);return b.length<2&&a>=2&&(b=b.padEnd(2,"0")),b.replace(/0/g,"")===""||!b?e:`${e}.${b}`}let g=["","K","M","B","T"],m=o===0?0:Math.floor(Math.log(o)/6.907755278982137);return`${(o/Math.pow(1e3,m)).toFixed(3).replace(/\.?0+$/,"")}${g[m]}`},c=(r,t=3)=>{let i=r.toString();if(t===-1)return i;let[s,e=""]=i.split(".");return e?`${s}.${e.substring(0,t).padEnd(t,"0")}`:i},T=(r,t="",i=1e5)=>u(r,i)+(t?` ${t}`:""),l=(r,t=18,i=1e5)=>u(f(r,t),i),w=(r,t=3)=>c(f(r),t),M=(r,t=18,i=3,s=1e5)=>{if(typeof r!="string")throw new Error("Invalid currency, must be a string");d(t);let e=r.trim()===""?"":` ${r.trim()}`;return{coinsToWeiInBigInt:n=>E(n,t),coinsToWei:n=>I(n,t),weiToCoins:n=>f(n,t),dangerouslyWeiToCoinsInFloat:n=>F(n,t),format:n=>u(n,s)+e,formatPrecise:(n,o=i)=>c(n,o)+e,formatPure:n=>u(n,s),formatPurePrecise:(n,o=i)=>c(n,o),weiFormat:n=>l(n,t,s)+e,weiFormatPrecise:(n,o=i)=>w(n,o)+e,weiFormatPure:n=>l(n,s),weiFormatPurePrecise:(n,o=i)=>w(n,o),inAllFormats:(n,o=i)=>{let g=I(n,t),m=n.toString();return{parsed:m,full:u(n,s)+e,precise:c(n,o)+e,exact:m+e,currency:r,wei:g}},weiInAllFormats:(n,o=i)=>{let g=f(n,t);return{parsed:g,full:u(g,s)+e,precise:c(g,o)+e,exact:g+e,currency:r,wei:n.toString()}}}};return $(_);})(); | ||
"use strict";var CoinFormat=(()=>{var F=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var _=(r,t)=>{for(var i in t)F(r,i,{get:t[i],enumerable:!0})},U=(r,t,i,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of $(t))!P.call(r,e)&&e!==i&&F(r,e,{get:()=>t[e],enumerable:!(o=B(t,e))||o.enumerable});return r};var y=r=>U(F({},"__esModule",{value:!0}),r);var W={};_(W,{Coin:()=>v,DEFAULT_DECIMALS:()=>N,cleanUpCoinsValue:()=>d,coinToGwei:()=>L,coinToWei:()=>E,coinToWeiInBigInt:()=>l,dangerouslyWeiToCoinInFloat:()=>D,formatFixed:()=>f,formatNice:()=>m,gweiToCoin:()=>T,gweiToWei:()=>A,weiFormatFixed:()=>p,weiFormatNice:()=>w,weiToCoin:()=>b,weiToGwei:()=>x});var N=18,S=r=>{if(typeof r!="number")throw new Error("Invalid decimals, must be a number");if(r<1||r>18)throw new Error("Invalid decimals, must be between 0 and 18");return!0},l=(r,t=18)=>{if(r=r.toString(),!/^\d+(\.\d+)?$/.test(r))throw new Error("Invalid value");S(t);let i=10n**BigInt(t),[o,e=""]=r.split(".");return e=e.padEnd(t,"0").slice(0,t),BigInt(o)*i+BigInt(e)},E=(r,t=18)=>l(r,t).toString(),b=(r,t=18)=>{S(t);let i=BigInt(r),o=10n**BigInt(t),e=i/o,s=(i%o).toString().padStart(t,"0").replace(/0+$/,"");return`${e}${s.length>0?"."+s:""}`},D=(r,t=18)=>parseFloat(b(r,t)),m=(r,t=1e5)=>{let i=typeof r=="string"?r:r.toString(),o=parseFloat(i);if(isNaN(o))throw new Error(`Coin.format: Invalid number: ${i}`);if(t===-1)return i;let[e,n=""]=i.split("."),g=parseInt(e);if(g<t){if(!n)return i;let M=parseFloat(`0.${n}`),a=0;M<.1?a=6:g<1?a=4:g<10?a=3:g<1e4?a=2:g<1e5&&(a=1);let c=n.substring(0,a);return c.length<2&&a>=2&&(c=c.padEnd(2,"0")),c.replace(/0/g,"")===""||!c?e:`${e}.${c}`}let s=["","K","M","B","T"],u=g===0?0:Math.min(Math.floor(Math.log(g)/6.907755278982137),4),[I,C=""]=(g/Math.pow(1e3,u)).toString().split(".");return`${I+(C.length>0?"."+C.slice(0,3):"")}${s[u]}`},f=(r,t=3)=>{let i=r.toString();if(t===-1)return i;let[o,e=""]=i.split(".");return e?`${o}.${e.substring(0,t).padEnd(t,"0")}`:i},w=(r,t=18,i=1e5)=>m(b(r,t),i),p=(r,t=18,i=3)=>f(b(r,t),i),x=(r,t=18)=>{let i=BigInt(r);if(i<0n)throw new Error("Invalid gwei value");let o=10n**(BigInt(t)/2n),[e,n=""]=[(i/o).toString(),(i%o).toString().padStart(t/2,"0").replace(/0+$/,"")];return n?`${e}.${n}`:e},A=(r,t=18)=>{let i=10n**(BigInt(t)/2n),[o,e=""]=r.toString().split(".");if(BigInt(o)<0n)throw new Error("Invalid gwei value - must be positive");let n=BigInt(o)*i;if(!e)return n.toString();let g=e.padEnd(t/2,"0").slice(0,t/2);return(n+BigInt(g)).toString()},L=(r,t=18)=>x(E(r,t),t),T=(r,t=18)=>b(A(r,t),t),d=r=>r.toString().trim().replace(/\.?0+$/,""),v=(r,t=18,i=3,o=1e5)=>{if(typeof r!="string")throw new Error("Invalid currency, must be a string");S(t);let e=r.trim()===""?"":` ${r.trim()}`;return{coinToWeiInBigInt:n=>l(n,t),coinToWei:n=>E(n,t),weiToCoin:n=>b(n,t),dangerouslyWeiToCoinInFloat:n=>D(n,t),formatNice:n=>m(n,o)+e,formatMetric:n=>m(n,o),formatFixed:(n,g=i)=>f(n,g)+e,formatFixedClean:(n,g=i)=>f(n,g),weiFormatNice:n=>w(n,t,o)+e,weiFormatMetric:n=>w(n,t,o),weiFormatFixed:(n,g=i)=>p(n,t,g)+e,weiFormatFixedClean:(n,g=i)=>p(n,t,g),gwei:{gweiToWei:n=>A(n,t),weiToGwei:n=>x(n,t),gweiToCoin:n=>T(n,t),coinToGwei:n=>L(n,t)},inAllFormats:(n,g=i)=>{let s=E(n,t),u=d(n),I=m(n,o);return{value:u,metric:I,nice:I+e,fixed:f(n,g)+e,exact:u+e,currency:r,wei:s}},weiInAllFormats:(n,g=i)=>{let s=b(n,t),u=w(n,t,o);return{value:s,metric:u,nice:u+e,fixed:p(n,t,g)+e,exact:s+e,currency:r,wei:n.toString()}}}};return y(W);})(); | ||
//# sourceMappingURL=index.min.js.map |
declare const DEFAULT_DECIMALS = 18; | ||
declare const coinsToWeiInBigInt: (value: string | number, decimals?: number) => bigint; | ||
declare const coinsToWei: (value: string | number, decimals?: number) => string; | ||
declare const weiToCoins: (weiValue: string | bigint, decimals?: number) => string; | ||
declare const dangerouslyWeiToCoinsInFloat: (weiValue: string | bigint, decimals?: number) => number; | ||
declare const format: (value: string | number, formattingThreshold?: number) => string; | ||
declare const formatPrecise: (value: string | number, precision?: number) => string; | ||
declare const formatWithCurrency: (value: string | number, currency?: string, formattingThreshold?: number) => string; | ||
declare const weiFormat: (weiValue: string | bigint, decimals?: number, formattingThreshold?: number) => string; | ||
declare const weiFormatPrecise: (weiValue: string | bigint, precision?: number) => string; | ||
declare const coinToWeiInBigInt: (value: string | number, decimals?: number) => bigint; | ||
declare const coinToWei: (value: string | number, decimals?: number) => string; | ||
declare const weiToCoin: (weiValue: string | bigint, decimals?: number) => string; | ||
declare const dangerouslyWeiToCoinInFloat: (weiValue: string | bigint, decimals?: number) => number; | ||
declare const formatNice: (value: string | number, formattingThreshold?: number) => string; | ||
declare const formatFixed: (value: string | number, precision?: number) => string; | ||
declare const weiFormatNice: (weiValue: string | bigint, decimals?: number, formattingThreshold?: number) => string; | ||
declare const weiFormatFixed: (weiValue: string | bigint, decimals?: number, precision?: number) => string; | ||
declare const weiToGwei: (gwei: string | bigint, decimals?: number) => string; | ||
declare const gweiToWei: (gwei: string | number | bigint, decimals?: number) => string; | ||
declare const coinToGwei: (value: string | number, decimals?: number) => string; | ||
declare const gweiToCoin: (value: string | number, decimals?: number) => string; | ||
declare const cleanUpCoinsValue: (value: string | number) => string; | ||
declare const Coin: (currency: string, decimals?: number, precision?: number, formattingThreshold?: number) => { | ||
coinsToWeiInBigInt: (value: string) => bigint; | ||
coinsToWei: (value: string) => string; | ||
weiToCoins: (value: string | bigint) => string; | ||
dangerouslyWeiToCoinsInFloat: (value: string | bigint) => number; | ||
format: (value: string) => string; | ||
formatPrecise: (value: string | number, _precision?: number) => string; | ||
formatPure: (value: string | number) => string; | ||
formatPurePrecise: (value: string | number, _precision?: number) => string; | ||
weiFormat: (value: string | bigint) => string; | ||
weiFormatPrecise: (value: string | bigint, _precision?: number) => string; | ||
weiFormatPure: (value: string | bigint) => string; | ||
weiFormatPurePrecise: (value: string | bigint, _precision?: number) => string; | ||
coinToWeiInBigInt: (value: string) => bigint; | ||
coinToWei: (value: string) => string; | ||
weiToCoin: (value: string | bigint) => string; | ||
dangerouslyWeiToCoinInFloat: (value: string | bigint) => number; | ||
formatNice: (value: string) => string; | ||
formatMetric: (value: string) => string; | ||
formatFixed: (value: string | number, _precision?: number) => string; | ||
formatFixedClean: (value: string | number, _precision?: number) => string; | ||
weiFormatNice: (value: string | bigint) => string; | ||
weiFormatMetric: (value: string | bigint) => string; | ||
weiFormatFixed: (value: string | bigint, _precision?: number) => string; | ||
weiFormatFixedClean: (value: string | bigint, _precision?: number) => string; | ||
gwei: { | ||
gweiToWei: (value: string | number | bigint) => string; | ||
weiToGwei: (value: string | bigint) => string; | ||
gweiToCoin: (value: string | number) => string; | ||
coinToGwei: (value: string | number) => string; | ||
}; | ||
inAllFormats: (value: string | number, _precision?: number) => ICoinFormats; | ||
@@ -28,5 +38,6 @@ weiInAllFormats: (wei: string | bigint, _precision?: number) => ICoinFormats; | ||
type ICoinFormats = { | ||
parsed: string; | ||
full: string; | ||
precise: string; | ||
value: string; | ||
metric: string; | ||
nice: string; | ||
fixed: string; | ||
exact: string; | ||
@@ -38,2 +49,2 @@ currency: string; | ||
export { Coin, DEFAULT_DECIMALS, type ICoin, type ICoinFormats, coinsToWei, coinsToWeiInBigInt, dangerouslyWeiToCoinsInFloat, format, formatPrecise, formatWithCurrency, weiFormat, weiFormatPrecise, weiToCoins }; | ||
export { Coin, DEFAULT_DECIMALS, type ICoin, type ICoinFormats, cleanUpCoinsValue, coinToGwei, coinToWei, coinToWeiInBigInt, dangerouslyWeiToCoinInFloat, formatFixed, formatNice, gweiToCoin, gweiToWei, weiFormatFixed, weiFormatNice, weiToCoin, weiToGwei }; |
159
index.js
@@ -25,11 +25,15 @@ "use strict"; | ||
DEFAULT_DECIMALS: () => DEFAULT_DECIMALS, | ||
coinsToWei: () => coinsToWei, | ||
coinsToWeiInBigInt: () => coinsToWeiInBigInt, | ||
dangerouslyWeiToCoinsInFloat: () => dangerouslyWeiToCoinsInFloat, | ||
format: () => format, | ||
formatPrecise: () => formatPrecise, | ||
formatWithCurrency: () => formatWithCurrency, | ||
weiFormat: () => weiFormat, | ||
weiFormatPrecise: () => weiFormatPrecise, | ||
weiToCoins: () => weiToCoins | ||
cleanUpCoinsValue: () => cleanUpCoinsValue, | ||
coinToGwei: () => coinToGwei, | ||
coinToWei: () => coinToWei, | ||
coinToWeiInBigInt: () => coinToWeiInBigInt, | ||
dangerouslyWeiToCoinInFloat: () => dangerouslyWeiToCoinInFloat, | ||
formatFixed: () => formatFixed, | ||
formatNice: () => formatNice, | ||
gweiToCoin: () => gweiToCoin, | ||
gweiToWei: () => gweiToWei, | ||
weiFormatFixed: () => weiFormatFixed, | ||
weiFormatNice: () => weiFormatNice, | ||
weiToCoin: () => weiToCoin, | ||
weiToGwei: () => weiToGwei | ||
}); | ||
@@ -45,3 +49,3 @@ module.exports = __toCommonJS(coin_exports); | ||
}; | ||
var coinsToWeiInBigInt = (value, decimals = DEFAULT_DECIMALS) => { | ||
var coinToWeiInBigInt = (value, decimals = DEFAULT_DECIMALS) => { | ||
value = value.toString(); | ||
@@ -58,6 +62,6 @@ if (!/^\d+(\.\d+)?$/.test(value)) { | ||
}; | ||
var coinsToWei = (value, decimals = DEFAULT_DECIMALS) => { | ||
return coinsToWeiInBigInt(value, decimals).toString(); | ||
var coinToWei = (value, decimals = DEFAULT_DECIMALS) => { | ||
return coinToWeiInBigInt(value, decimals).toString(); | ||
}; | ||
var weiToCoins = (weiValue, decimals = DEFAULT_DECIMALS) => { | ||
var weiToCoin = (weiValue, decimals = DEFAULT_DECIMALS) => { | ||
validateDecimals(decimals); | ||
@@ -73,4 +77,4 @@ const weiBigInt = BigInt(weiValue); | ||
}; | ||
var dangerouslyWeiToCoinsInFloat = (weiValue, decimals = DEFAULT_DECIMALS) => parseFloat(weiToCoins(weiValue, decimals)); | ||
var format = (value, formattingThreshold = 1e5) => { | ||
var dangerouslyWeiToCoinInFloat = (weiValue, decimals = DEFAULT_DECIMALS) => parseFloat(weiToCoin(weiValue, decimals)); | ||
var formatNice = (value, formattingThreshold = 1e5) => { | ||
const numStr = typeof value === "string" ? value : value.toString(); | ||
@@ -110,8 +114,8 @@ const roughNum = parseFloat(numStr); | ||
const suffixes = ["", "K", "M", "B", "T"]; | ||
const i = integerNum === 0 ? 0 : Math.floor(Math.log(integerNum) / 6.907755278982137); | ||
const withPossibleTrailingZeroes = (integerNum / Math.pow(1e3, i)).toFixed(3); | ||
const formatted = withPossibleTrailingZeroes.replace(/\.?0+$/, ""); | ||
const i = integerNum === 0 ? 0 : Math.min(Math.floor(Math.log(integerNum) / 6.907755278982137), 4); | ||
const [integerPartOfNice, fractionalPartOfNice = ""] = (integerNum / Math.pow(1e3, i)).toString().split("."); | ||
const formatted = integerPartOfNice + (fractionalPartOfNice.length > 0 ? "." + fractionalPartOfNice.slice(0, 3) : ""); | ||
return `${formatted}${suffixes[i]}`; | ||
}; | ||
var formatPrecise = (value, precision = 3) => { | ||
var formatFixed = (value, precision = 3) => { | ||
const numStr = value.toString(); | ||
@@ -125,11 +129,42 @@ if (precision === -1) | ||
}; | ||
var formatWithCurrency = (value, currency = "", formattingThreshold = 1e5) => { | ||
return format(value, formattingThreshold) + (currency ? ` ${currency}` : ""); | ||
var weiFormatNice = (weiValue, decimals = DEFAULT_DECIMALS, formattingThreshold = 1e5) => { | ||
return formatNice(weiToCoin(weiValue, decimals), formattingThreshold); | ||
}; | ||
var weiFormat = (weiValue, decimals = DEFAULT_DECIMALS, formattingThreshold = 1e5) => { | ||
return format(weiToCoins(weiValue, decimals), formattingThreshold); | ||
var weiFormatFixed = (weiValue, decimals = DEFAULT_DECIMALS, precision = 3) => { | ||
return formatFixed(weiToCoin(weiValue, decimals), precision); | ||
}; | ||
var weiFormatPrecise = (weiValue, precision = 3) => { | ||
return formatPrecise(weiToCoins(weiValue), precision); | ||
var weiToGwei = (gwei, decimals = DEFAULT_DECIMALS) => { | ||
const weiBigInt = BigInt(gwei); | ||
if (weiBigInt < 0n) | ||
throw new Error("Invalid gwei value"); | ||
const divisor = 10n ** (BigInt(decimals) / 2n); | ||
const [integerPart, fractionalPart = ""] = [ | ||
(weiBigInt / divisor).toString(), | ||
(weiBigInt % divisor).toString().padStart(decimals / 2, "0").replace(/0+$/, "") | ||
]; | ||
if (!fractionalPart) | ||
return integerPart; | ||
return `${integerPart}.${fractionalPart}`; | ||
}; | ||
var gweiToWei = (gwei, decimals = DEFAULT_DECIMALS) => { | ||
const multiplier = 10n ** (BigInt(decimals) / 2n); | ||
const [integerPart, fractionalPart = ""] = gwei.toString().split("."); | ||
if (BigInt(integerPart) < 0n) | ||
throw new Error("Invalid gwei value - must be positive"); | ||
const gweiIntegerPartInWei = BigInt(integerPart) * multiplier; | ||
if (!fractionalPart) | ||
return gweiIntegerPartInWei.toString(); | ||
const fractionalPartStr = fractionalPart.padEnd(decimals / 2, "0").slice(0, decimals / 2); | ||
const weiValue = gweiIntegerPartInWei + BigInt(fractionalPartStr); | ||
return weiValue.toString(); | ||
}; | ||
var coinToGwei = (value, decimals = DEFAULT_DECIMALS) => { | ||
return weiToGwei(coinToWei(value, decimals), decimals); | ||
}; | ||
var gweiToCoin = (value, decimals = DEFAULT_DECIMALS) => { | ||
return weiToCoin(gweiToWei(value, decimals), decimals); | ||
}; | ||
var cleanUpCoinsValue = (value) => { | ||
return value.toString().trim().replace(/\.?0+$/, ""); | ||
}; | ||
var Coin = (currency, decimals = DEFAULT_DECIMALS, precision = 3, formattingThreshold = 1e5) => { | ||
@@ -141,21 +176,29 @@ if (typeof currency !== "string") | ||
return { | ||
coinsToWeiInBigInt: (value) => coinsToWeiInBigInt(value, decimals), | ||
coinsToWei: (value) => coinsToWei(value, decimals), | ||
weiToCoins: (value) => weiToCoins(value, decimals), | ||
dangerouslyWeiToCoinsInFloat: (value) => dangerouslyWeiToCoinsInFloat(value, decimals), | ||
format: (value) => format(value, formattingThreshold) + paddedCurrency, | ||
formatPrecise: (value, _precision = precision) => formatPrecise(value, _precision) + paddedCurrency, | ||
formatPure: (value) => format(value, formattingThreshold), | ||
formatPurePrecise: (value, _precision = precision) => formatPrecise(value, _precision), | ||
weiFormat: (value) => weiFormat(value, decimals, formattingThreshold) + paddedCurrency, | ||
weiFormatPrecise: (value, _precision = precision) => weiFormatPrecise(value, _precision) + paddedCurrency, | ||
weiFormatPure: (value) => weiFormat(value, formattingThreshold), | ||
weiFormatPurePrecise: (value, _precision = precision) => weiFormatPrecise(value, _precision), | ||
coinToWeiInBigInt: (value) => coinToWeiInBigInt(value, decimals), | ||
coinToWei: (value) => coinToWei(value, decimals), | ||
weiToCoin: (value) => weiToCoin(value, decimals), | ||
dangerouslyWeiToCoinInFloat: (value) => dangerouslyWeiToCoinInFloat(value, decimals), | ||
formatNice: (value) => formatNice(value, formattingThreshold) + paddedCurrency, | ||
formatMetric: (value) => formatNice(value, formattingThreshold), | ||
formatFixed: (value, _precision = precision) => formatFixed(value, _precision) + paddedCurrency, | ||
formatFixedClean: (value, _precision = precision) => formatFixed(value, _precision), | ||
weiFormatNice: (value) => weiFormatNice(value, decimals, formattingThreshold) + paddedCurrency, | ||
weiFormatMetric: (value) => weiFormatNice(value, decimals, formattingThreshold), | ||
weiFormatFixed: (value, _precision = precision) => weiFormatFixed(value, decimals, _precision) + paddedCurrency, | ||
weiFormatFixedClean: (value, _precision = precision) => weiFormatFixed(value, decimals, _precision), | ||
gwei: { | ||
gweiToWei: (value) => gweiToWei(value, decimals), | ||
weiToGwei: (value) => weiToGwei(value, decimals), | ||
gweiToCoin: (value) => gweiToCoin(value, decimals), | ||
coinToGwei: (value) => coinToGwei(value, decimals) | ||
}, | ||
inAllFormats: (value, _precision = precision) => { | ||
const wei = coinsToWei(value, decimals); | ||
const coins = value.toString(); | ||
const wei = coinToWei(value, decimals); | ||
const coins = cleanUpCoinsValue(value); | ||
const metric = formatNice(value, formattingThreshold); | ||
return { | ||
parsed: coins, | ||
full: format(value, formattingThreshold) + paddedCurrency, | ||
precise: formatPrecise(value, _precision) + paddedCurrency, | ||
value: coins, | ||
metric, | ||
nice: metric + paddedCurrency, | ||
fixed: formatFixed(value, _precision) + paddedCurrency, | ||
exact: coins + paddedCurrency, | ||
@@ -167,7 +210,9 @@ currency, | ||
weiInAllFormats: (wei, _precision = precision) => { | ||
const coins = weiToCoins(wei, decimals); | ||
const coins = weiToCoin(wei, decimals); | ||
const metric = weiFormatNice(wei, decimals, formattingThreshold); | ||
return { | ||
parsed: coins, | ||
full: format(coins, formattingThreshold) + paddedCurrency, | ||
precise: formatPrecise(coins, _precision) + paddedCurrency, | ||
value: coins, | ||
metric, | ||
nice: metric + paddedCurrency, | ||
fixed: weiFormatFixed(wei, decimals, _precision) + paddedCurrency, | ||
exact: coins + paddedCurrency, | ||
@@ -184,12 +229,16 @@ currency, | ||
DEFAULT_DECIMALS, | ||
coinsToWei, | ||
coinsToWeiInBigInt, | ||
dangerouslyWeiToCoinsInFloat, | ||
format, | ||
formatPrecise, | ||
formatWithCurrency, | ||
weiFormat, | ||
weiFormatPrecise, | ||
weiToCoins | ||
cleanUpCoinsValue, | ||
coinToGwei, | ||
coinToWei, | ||
coinToWeiInBigInt, | ||
dangerouslyWeiToCoinInFloat, | ||
formatFixed, | ||
formatNice, | ||
gweiToCoin, | ||
gweiToWei, | ||
weiFormatFixed, | ||
weiFormatNice, | ||
weiToCoin, | ||
weiToGwei | ||
}); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "coin-format", | ||
"version": "0.0.1", | ||
"version": "0.0.2", | ||
"description": "A tiny zero-dependency library to format coins, primarily for crypto, with broader applications as well.", | ||
@@ -13,3 +13,3 @@ "main": "index.js", | ||
}, | ||
"homepage": "https://github.com/fend25/coin-format#readme", | ||
"homepage": "https://github.com/fend25/coin-format", | ||
"private": false, | ||
@@ -16,0 +16,0 @@ "keywords": [ |
267
README.md
# Coin Format | ||
A tiny library for handling and formatting cryptocurrency values in JavaScript and TypeScript. | ||
<img width="256" height="256" src="https://raw.githubusercontent.com/fend25/coin-format/main/logo.svg" alt="Coin Format library logo"/> | ||
[//]: # (![Coin Format logo](https://raw.githubusercontent.com/fend25/coin-format/main/logo.svg) | ||
A tiny library for handling and formatting cryptocurrency values in JavaScript and TypeScript. Truly, a concise and self-explanatory Swiss Army knife for coin value conversion and formatting. | ||
Zero dependencies. 1.2 Kb minified and compressed. Compatible with both browsers and Node, though it does necessitate support for BigInt (Node 12+, browsers 2020+). | ||
@@ -9,16 +13,47 @@ | ||
## Introduction | ||
```typescript | ||
coinToWei('1.2') // "1200000000000000000" | ||
coinToWei('1.2', 8) // "120000000" - for btc or other coins with different decimals | ||
weiToCoin('50000000000000000') // "0.05" | ||
The `coin-format` library is designed to simplify the handling and formatting of cryptocurrency values in various formats. It provides a versatile pseudoclass, `Coin`, for managing currency values with support for converting between "coins" and "wei" (the smallest denomination), formatting numbers, and rendering them in human-readable forms. | ||
const eth = Coin('ETH') | ||
eth.coinToWei('1.5') // "1500000000000000000" | ||
eth.weiToCoin('1500000000000000000') // "1.5" | ||
## Installation | ||
eth.formatNice('1234567.56') // "1.234M ETH" | ||
eth.formatFixed('0.0010002') // "0.001 ETH" | ||
To use `coin-format` in your project, add it to your dependencies: | ||
eth.weiFormatNice('1234567890123456789000000') // "1.234M ETH" | ||
eth.weiFormatFixed('1234567890123456789000') // "1234.567 ETH" | ||
eth.inAllFormats('1234567.89') | ||
// { | ||
// value: '1234567.89', | ||
// exact: '1234567.89 ETH', | ||
// nice: '1.234M ETH', | ||
// metric: '1.234M', | ||
// fixed: '1234567.890 ETH', | ||
// wei: '1234567890000000000000000', | ||
// currency: 'ETH', | ||
// } | ||
eth.weiInAllFormats('1234567890000000000000000') // same output | ||
eth.gwei.gweiToWei('1') // "1000000000" | ||
eth.gwei.weiToGwei('5678000000') // "5.678" | ||
eth.gwei.gweiToCoin('1234000000') // "1.234" | ||
eth.gwei.coinToGwei('1.234') // "1234000000" | ||
``` | ||
And much more! Please continue reading below for a comprehensive guide to all the features and functionalities the library offers. | ||
## Usage | ||
The `coin-format` library is designed to simplify the handling and formatting of cryptocurrency values in various formats. It provides a versatile pseudoclass, `Coin`, for managing currency values with support for converting between "coins" and "wei" (the smallest denomination), formatting numbers, and rendering them in human-readable forms. | ||
Installation: | ||
``` | ||
npm install coin-format | ||
``` | ||
## Usage | ||
First, import the `Coin` pseudoclass from the library: | ||
@@ -37,5 +72,16 @@ | ||
// 6 - precision (number of decimal places to consider in *Precise methods) | ||
// 100 - formatting threshold (number more than 100 will be formatted with metric suffixes) | ||
// 100 - formatting threshold (number more than 100 will be formatted with metric suffixes - K, M, B, T, etc.) | ||
``` | ||
Default threshold is 100000 (100K), so values like "1234.56" and "99999.99" will be formatted as is, but "100000" will be formatted as "100K". If set the threshold to 1000, then "1234.56" will be formatted as "1.234K". | ||
**IMPORTANT**: | ||
> **All formatters always do truncation (flooring), not rounding.** | ||
> | ||
> So, "1234.5678" will be formatted as "1234.567", not "1234.568". | ||
> | ||
> And "1234999.99" will be formatted as "1.234M", not "1.235M". | ||
> | ||
> It's done to avoid confusion with the actual value, because it's used for money and overestimation is not acceptable. | ||
### Formatting Values | ||
@@ -45,6 +91,6 @@ | ||
- `coinsToWei` and `coinsToWeiInBigInt`: Convert coin values to wei. | ||
- `weiToCoins`: Convert wei values to coin values. | ||
- `format` and `formatPrecise`: Format coin values with or without specified precision. | ||
- `weiFormat` and `weiFormatPrecise`: Format wei values in the coin format. | ||
- `coinToWei` and `coinToWeiInBigInt`: Convert coin values to wei. | ||
- `weiToCoin`: Convert wei values to coin values. | ||
- `formatNice` and `formatFixed`: Format coin values with or without specified precision. | ||
- `weiFormatNice` and `weiFormatFixed`: Format wei values in the coin formatNice. | ||
@@ -58,4 +104,4 @@ ### Example | ||
eth.coinsToWei('1234.56') // Outputs: "1234560000000000000000" | ||
eth.weiToCoins('1234567890123456789000') // Outputs: "1234.567890123456789" | ||
eth.coinToWei('1234.56') // Outputs: "1234560000000000000000" | ||
eth.weiToCoin('1234567890123456789000') // Outputs: "1234.567890123456789" | ||
``` | ||
@@ -69,8 +115,17 @@ | ||
import { Coin } from 'coin-format' | ||
const eth = Coin('ETH') | ||
const btc = Coin('BTC', 8, 6, 100) | ||
eth.format('1234.56') // Outputs: "1.235K ETH" | ||
btc.formatPrecise('1234.56') // Outputs: "1234.560000 BTC" | ||
eth.weiFormat('1234567890123456789000') // Outputs: "1234.567890 ETH" | ||
eth.weiFormat('1234567890123456789000000') // Outputs: "1234.56 ETH" | ||
btc.weiFormatPrecise('123456789012') // Outputs: "1234.567890 BTC" | ||
eth.formatNice('1234.56') // Outputs: "1234.56 ETH" | ||
eth.formatMetric('1234.56') // Outputs: "1234.56" | ||
btc.formatFixed('1234.56') // Outputs: "1234.560000 BTC" | ||
btc.formatFixedClean('1234.56') // Outputs: "1234.560000" | ||
eth.weiFormatNice('1234567890123456789000') // Outputs: "1234.567890 ETH" | ||
eth.weiFormatMetric('1234567890123456789000') // Outputs: "1234.567890" | ||
btc.weiFormatMetric('1234567890123') // Outputs: "1234.567890" | ||
btc.weiFormatFixed('123456789012') // Outputs: "1234.567890 BTC" | ||
btc.weiFormatFixedClean('123456789012') // Outputs: "1234.567890" | ||
``` | ||
@@ -84,17 +139,32 @@ | ||
const eth = Coin('ETH') | ||
const btc = Coin('BTC', 8, 6, 100) | ||
const btc = Coin('BTC', 8, 6, 100) // starting with 100, `nice` property will try to fold the value with metric suffixes (K, M, B, T, etc.) | ||
``` | ||
`eth.inAllFormats('1199.99999000')` will output: | ||
`eth.inAllFormats('1199.9')` will output: | ||
``` | ||
{ | ||
value: '1199.99999', | ||
exact: '1199.99999 ETH', | ||
nice: '1199.99 ETH', | ||
metric: '1199.99', | ||
fixed: '1199.999 ETH', | ||
wei: '1199999990000000000000', | ||
currency: 'ETH', | ||
} | ||
``` | ||
`eth.inAllFormats('1234567.8999')` will output: | ||
``` | ||
{ | ||
parsed: '1199.9', | ||
exact: '1199.9 ETH', | ||
full: '1199.90 ETH', | ||
precise: '1199.900 ETH', | ||
wei: '1199900000000000000000', | ||
value: '1234567.8999', | ||
exact: '1234567.8999 ETH', | ||
nice: '1.234M ETH', | ||
metric: '1.234M', | ||
fixed: '1234567.899 ETH', | ||
wei: '1234567899900000000000000', | ||
currency: 'ETH', | ||
} | ||
``` | ||
@@ -106,6 +176,7 @@ | ||
{ | ||
parsed: '1199.5', | ||
value: '1199.5', | ||
exact: '1199.5 BTC', | ||
full: '1.199K BTC', | ||
precise: '1199.500000 BTC', | ||
nice: '1.199K BTC', | ||
metric: '1.199K', | ||
fixed: '1199.500000 BTC', | ||
wei: '119950000000', | ||
@@ -116,6 +187,142 @@ currency: 'BTC', | ||
#### Gwei conversion | ||
The `Coin` pseudoclass includes a `gwei` object that provides utility methods for converting between Gwei, Wei, and coin denominations. This feature is essential for Ethereum and other blockchain technologies that use these units for transactions and gas calculations. It depends on the decimal value, effectively halving it to determine the Gwei multiplier (10^9 for 18 decimals). | ||
##### Methods | ||
- `gweiToWei(value: string | number | bigint): string` - Converts Gwei to Wei. | ||
- `weiToGwei(value: string | bigint): string` - Converts Wei to Gwei. | ||
- `gweiToCoin(value: string | number): string` - Converts Gwei to the main coin denomination. | ||
- `coinToGwei(value: string | number): string` - Converts the main coin denomination to Gwei. | ||
##### Usage Examples | ||
```typescript | ||
const eth = Coin('ETH') | ||
eth.gwei.gweiToWei('1') // outputs: "1000000000" (wei) | ||
eth.gwei.weiToGwei('5678000000') // outputs: "5.678" (gwei) | ||
eth.gwei.gweiToCoin('1234000000') // outputs: "1.234" (eth) | ||
eth.gwei.coinToGwei('1.234') // outputs: "1234000000" (gwei) | ||
``` | ||
## Examples | ||
#### Wei-Coin conversion | ||
```typescript | ||
import { Coin, weiToCoin, coinToWei } from 'coin-format' | ||
coinToWei('1.2') // outputs: "1200000000000000000" | ||
coinToWei('1.2', 8) // outputs: "120000000" | ||
weiToCoin('500000000000000000') // outputs: "0.5" | ||
weiToCoin('150000000', 8) // outputs: "1.5" | ||
// All underlying operations are performed using strings, | ||
// ensuring precise conversions without rounding or loss of precision. | ||
weiToCoin(1n) // outputs: "0.000000000000000001" | ||
// Therefore, avoid using the `dangerouslyWeiToCoinInFloat` method unless you understand the risks, | ||
// including unpredictable value rounding and discrepancies from the actual value. | ||
``` | ||
Of course, Coin contains the same methods and even more | ||
```typescript | ||
const eth = Coin('ETH') | ||
eth.coinToWei('1.5') // outputs: "1500000000000000000" | ||
eth.weiToCoin('1500000000000000000') // outputs: "1.5" | ||
eth.weiToCoin(1n) // outputs: "0.000000000000000001" | ||
const btc = Coin('BTC', 8) | ||
btc.coinToWei('0.00015') // outputs: "15000" (satoshis) | ||
btc.weiToCoin('24000') // outputs: "0.00024" | ||
``` | ||
#### Formatting | ||
```typescript | ||
const eth = Coin('ETH') // Defaults settings - decimals: 18, precision: 6, threshold: 100000 | ||
// regular values | ||
eth.formatNice('1199.9999') // outputs: "1199.99 ETH" | ||
eth.formatFixed('1199.9999') // outputs: "1199.999 ETH" | ||
eth.weiFormatNice('1199999900000000000000') // outputs: "1199.99 ETH" | ||
// big values | ||
eth.formatNice('1234567.9999') // outputs: "1.234M ETH" | ||
eth.formatFixed('1234567.9999') // outputs: "1234567.999 ETH" | ||
eth.weiFormatNice('1234567999900000000000000') // outputs: "1.234M ETH" | ||
// small values | ||
eth.formatNice('0.000001') // outputs: "0.000001 ETH" | ||
eth.formatNice('0.0000001') // outputs: "0 ETH" | ||
eth.formatFixed('0.0001') // outputs: "0.000 ETH" | ||
eth.weiFormatNice('10000000000000000') // outputs: "0.01 ETH" | ||
eth.weiFormatFixed('10000000000000000') // outputs: "0.010 ETH" | ||
eth.weiFormatFixed('10', 17) // outputs: "0.00000000000000001 ETH" | ||
// in all formats | ||
eth.inAllFormats('1234567.9999') | ||
eth.inAllFormats('1234567.999') | ||
// { | ||
// value: '1234567.9999', | ||
// nice: '1.234M ETH', | ||
// metric: '1.234M', | ||
// fixed: '1234567.999 ETH', | ||
// exact: '1234567.9999 ETH', | ||
// currency: 'ETH', | ||
// wei: '1234567999900000000000000' | ||
// } | ||
eth.weiInAllFormats('123456700000000000') | ||
// { | ||
// value: '0.1234567', | ||
// nice: '0.1234 ETH', | ||
// metric: '0.1234', | ||
// fixed: '0.123 ETH', | ||
// exact: '0.1234567 ETH', | ||
// currency: 'ETH', | ||
// wei: '123456700000000000' | ||
// } | ||
``` | ||
##### Formatting without currency suffix | ||
```typescript | ||
const btc = Coin('BTC', 8, 6, 100) | ||
btc.formatNice('1234.567890') // Outputs: "1.234K BTC" | ||
btc.formatMetric('1234.567890') // Outputs: "1.234K" | ||
btc.formatFixed('1234.567890') // Outputs: "1234.567890 BTC" | ||
btc.formatFixedClean('1234.567890') // Outputs: "1234.567890" | ||
btc.weiFormatNice('123456789012') // Outputs: "1.234K BTC" | ||
btc.weiFormatMetric('123456789012') // Outputs: "1.234K" | ||
btc.weiFormatFixed('123456789012') // Outputs: "1234.567890 BTC" | ||
btc.weiFormatFixedClean('123456789012') // Outputs: "1234.567890" | ||
``` | ||
#### Gwei conversion | ||
```typescript | ||
const eth = Coin('ETH') | ||
eth.gwei.gweiToWei('1') // outputs: "1000000000" (wei) | ||
eth.gwei.weiToGwei('5678000000') // outputs: "5.678" (gwei) | ||
eth.gwei.gweiToCoin('1234000000') // outputs: "1.234" (eth) | ||
eth.gwei.coinToGwei('1.234') // outputs: "1234000000" (gwei) | ||
``` | ||
## Notes | ||
- The 'Nice' and 'Fixed' formatters always perform truncation (flooring), not rounding. This approach is used to avoid confusion with the actual value, as overestimation is not acceptable in financial contexts. | ||
- Ensure to handle large numbers as strings or `bigint` to avoid precision issues common with floating-point arithmetic in JavaScript. | ||
- The `dangerouslyWeiToCoinsInFloat` method should be used sparingly due to the inherent risk of losing precision when dealing with rounding in JS. | ||
- The `dangerouslyWeiToCoinInFloat` method should be used sparingly due to the inherent risk of losing precision when dealing with rounding in JS. | ||
@@ -122,0 +329,0 @@ ## Contributing |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
89441
536
328