Skip to content

Instantly share code, notes, and snippets.

@beigirad
Last active April 8, 2020 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beigirad/b87ffffd69dbbeecde9906fa9668e4fa to your computer and use it in GitHub Desktop.
Save beigirad/b87ffffd69dbbeecde9906fa9668e4fa to your computer and use it in GitHub Desktop.
price formatter
/*
expected functionality:
// 1002.0 -> 1,002
// 1002.1 -> 1,002.10
// 1002.666 -> 1,002.66
*/
fun legacyFormatPrice(value: Double) {
return if (this.rem(1) == 0.0)
String.format("%,.0f", value)
else
String.format("%,.2f", value)
}
fun formatPrice(value: Double, addSeparator: Boolean): String {
val fractionSize = 2
val separatorSize = 3
val fraction = BigDecimal((value % 1f) * 10.0.pow(fractionSize.toDouble()))
.setScale(0, RoundingMode.HALF_UP)
.toInt()
val integer = BigDecimal(value)
.setScale(0, RoundingMode.DOWN)
val builder = StringBuilder().append(integer)
val chunks = builder.length / separatorSize
if (addSeparator) {
var i = chunks * separatorSize
while (i > 0) {
val position = builder.length - i
if (position > 0)
builder.insert(position, ",")
i -= separatorSize
}
}
if (fraction > 0) {
builder.append(".")
var i = fractionSize - fraction.toString().length
while (i > 0) {
builder.append(0)
i--
}
builder.append(fraction)
}
return builder.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment