Last active
June 21, 2019 03:42
-
-
Save viclm/04f023f61e4fdceeb112016266119844 to your computer and use it in GitHub Desktop.
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
const rdot = /\.(\d*)$/ | |
const rleadzero = /^0+/ | |
function toIntStr(number) { | |
let string = number.toString() | |
let exponent = 0 | |
string = string | |
.replace(rdot, (str, p) => { | |
exponent = p.length | |
return p | |
}) | |
.replace(rleadzero, '') | |
return { | |
string, | |
exponent | |
} | |
} | |
function toFloatStr(string, exponent) { | |
if (exponent) { | |
let length = string.length | |
if (exponent < length) { | |
string = string.substr(0, length - exponent) + '.' + string.substr(length - exponent) | |
} | |
else { | |
string = '0.' + Array(exponent - length + 1).join('0') + string | |
} | |
} | |
return string | |
} | |
export const yuan2fen = function yuan2fen(amount) { | |
let symbol = amount < 0 ? -1 : 1 | |
let result = toIntStr(amount * symbol) | |
let fen = toFloatStr(result.string + '00', result.exponent) | |
return Number(fen) * symbol | |
} | |
export const fen2yuan = function yuan2fen(amount) { | |
let symbol = amount < 0 ? -1 : 1 | |
let result = toIntStr(amount * symbol) | |
let yuan = toFloatStr(result.string, result.exponent + 2) | |
return Number(yuan) * symbol | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment