Category talk:Wren-big: Difference between revisions
→Source code: Added an option to truncate rather than round to the BigRat.toDecimal method.
(→Source code: Added BigRat and BigRats classes.) |
(→Source code: Added an option to truncate rather than round to the BigRat.toDecimal method.) |
||
Line 1,510:
toInt { this.toFloat.truncate }
// Returns the decimal representation of this BigRat object to 'digits' decimal places
// If 'rounded' is true, the value is rounded to that number of places with halves
// being rounded away from zero. Otherwise the value is truncated to that number of places.
toDecimal(digits, rounded) {
if (!(digits is Num && digits.isInteger && digits >= 0)) {
Fiber.abort("Argument must be a non-negative integer")
Line 1,520 ⟶ 1,521:
if (this.isNegative && qr[0] == 0) intPart = "-" + intPart
var rem = BigRat.new(qr[1].abs, _d)
// need to allow an extra digit
var
var shiftedRem = rem * BigRat.new("1e" + digits2.toString, BigInt.one)
var decPart = (shiftedRem.num / shiftedRem.den).toString
var finalByte = decPart[-1].bytes[0]
decPart = (BigInt.new(decPart) + 5).toString
}
decPart = decPart[0...-1] // remove last digit▼
}
▲ decPart = decPart[0...-1] // remove last digit
if (decPart.count < digits) {
decPart = ("0" * (digits - decPart.count
}
if ((shiftedRem.num % shiftedRem.den) == BigInt.zero) {
Line 1,539 ⟶ 1,543:
}
// Convenience
toDecimal(digits) { toDecimal(
toDecimal { toDecimal(14, true) } // 14 digits, always rounded
// Returns a string represenation of this instance in the form "i_n/d" where 'i' is an integer.
|