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 accuracy.
// If 'rounded' is true, the value is rounded to that number of places with halves
// Halves are rounded away from zero.
// 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 for subsequentif 'rounding' is true
var shiftedRemdigits2 = rem(rounded) *? BigRat.new("1e"digits + (digits+1).toString, BigInt.one): digits
var shiftedRem = rem * BigRat.new("1e" + digits2.toString, BigInt.one)
var decPart = (shiftedRem.num / shiftedRem.den).toString
varif finalByte(rounded) = decPart[-1].bytes[0]{
var finalByte = decPart[-1].bytes[0]
if (finalByte >= 53) { // last character >= 5
decPartif (finalByte >= (BigInt.new(decPart53) +{ // last character >= 5).toString
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 + 1)) + decPart
}
if ((shiftedRem.num % shiftedRem.den) == BigInt.zero) {
Line 1,539 ⟶ 1,543:
}
 
// Convenience versionversions of the above which uses ause default valuevalues offor 14one decimalor placesboth accuracyparameters.
toDecimal(digits) { toDecimal(14digits, true) } // always rounded
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.
9,476

edits