Skip to main content

dashu_float/
convert.rs

1use core::{
2    convert::{TryFrom, TryInto},
3    num::FpCategory,
4};
5
6use dashu_base::{
7    Approximation::*, BitTest, ConversionError, DivRemEuclid, EstimatedLog2, FloatEncoding, Sign,
8    Signed,
9};
10use dashu_int::{IBig, UBig, Word};
11
12use crate::{
13    error::{assert_finite, panic_unlimited_precision, FpError},
14    fbig::FBig,
15    math::cache::{reborrow_cache, ConstCache},
16    repr::{Context, Repr},
17    round::{
18        mode::{HalfAway, HalfEven, Zero},
19        Round, Rounded, Rounding,
20    },
21    utils::{factor_base, ilog_exact, shl_digits, shl_digits_in_place, shr_digits},
22};
23
24impl<R: Round> Context<R> {
25    /// Convert an [IBig] instance to a [FBig] instance with precision
26    /// and rounding given by the context.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// # use core::str::FromStr;
32    /// # use dashu_base::ParseError;
33    /// # use dashu_float::DBig;
34    /// use dashu_base::Approximation::*;
35    /// use dashu_float::{Context, round::{mode::HalfAway, Rounding::*}};
36    ///
37    /// let context = Context::<HalfAway>::new(2);
38    /// assert_eq!(context.convert_int::<10>((-12).into()), Exact(DBig::from_str("-12")?));
39    /// assert_eq!(
40    ///     context.convert_int::<10>(5678.into()),
41    ///     Inexact(DBig::from_str("5.7e3")?, AddOne)
42    /// );
43    /// # Ok::<(), ParseError>(())
44    /// ```
45    pub fn convert_int<const B: Word>(&self, n: IBig) -> Rounded<FBig<R, B>> {
46        let repr = Repr::<B>::new(n, 0);
47        self.repr_round(repr).map(|v| FBig::new(v, *self))
48    }
49}
50
51macro_rules! impl_from_float_for_fbig {
52    ($t:ty) => {
53        impl TryFrom<$t> for Repr<2> {
54            type Error = ConversionError;
55
56            fn try_from(f: $t) -> Result<Self, Self::Error> {
57                match f.decode() {
58                    Ok((man, exp)) => Ok(if man == 0 && f.is_sign_negative() {
59                        Self::neg_zero()
60                    } else {
61                        Repr::new(man.into(), exp as _)
62                    }),
63                    Err(FpCategory::Infinite) => match f.sign() {
64                        Sign::Positive => Ok(Self::infinity()),
65                        Sign::Negative => Ok(Self::neg_infinity()),
66                    },
67                    _ => Err(ConversionError::OutOfBounds), // NaN
68                }
69            }
70        }
71
72        impl<R: Round> TryFrom<$t> for FBig<R, 2> {
73            type Error = ConversionError;
74
75            fn try_from(f: $t) -> Result<Self, Self::Error> {
76                match f.decode() {
77                    Ok((man, exp)) => {
78                        // preserve the sign of a signed zero (-0.0 -> Repr::neg_zero())
79                        let repr = if man == 0 && f.is_sign_negative() {
80                            Repr::neg_zero()
81                        } else {
82                            Repr::new(man.into(), exp as _)
83                        };
84
85                        // The precision is inferenced from the mantissa, because the mantissa of
86                        // normal float is always normalized. This will produce correct precision
87                        // for subnormal floats
88                        let bits = man.unsigned_abs().bit_len();
89                        let context = Context::new(bits);
90                        Ok(Self::new(repr, context))
91                    }
92                    Err(FpCategory::Infinite) => match f.sign() {
93                        Sign::Positive => Ok(Self::INFINITY),
94                        Sign::Negative => Ok(Self::NEG_INFINITY),
95                    },
96                    _ => Err(ConversionError::OutOfBounds), // NaN
97                }
98            }
99        }
100    };
101}
102
103impl_from_float_for_fbig!(f32);
104impl_from_float_for_fbig!(f64);
105
106impl<R: Round, const B: Word> FBig<R, B> {
107    /// Convert the float number to base 10 (with decimal exponents) rounding to even
108    /// and tying away from zero.
109    ///
110    /// It's equivalent to `self.with_rounding::<HalfAway>().with_base::<10>()`.
111    /// The output is directly of type [DBig][crate::DBig].
112    ///
113    /// See [with_base()][Self::with_base] for the precision behavior.
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// # use core::str::FromStr;
119    /// # use dashu_base::ParseError;
120    /// # use dashu_float::{FBig, DBig};
121    /// use dashu_base::Approximation::*;
122    /// use dashu_float::round::Rounding::*;
123    ///
124    /// type Real = FBig;
125    ///
126    /// assert_eq!(
127    ///     Real::from_str("0x1234")?.to_decimal(),
128    ///     Exact(DBig::from_str("4660")?)
129    /// );
130    /// assert_eq!(
131    ///     Real::from_str("0x12.34")?.to_decimal(),
132    ///     Inexact(DBig::from_str("18.20")?, NoOp)
133    /// );
134    /// assert_eq!(
135    ///     Real::from_str("0x1.234p-4")?.to_decimal(),
136    ///     Inexact(DBig::from_str("0.07111")?, AddOne)
137    /// );
138    /// # Ok::<(), ParseError>(())
139    /// ```
140    ///
141    /// # Panics
142    ///
143    /// Panics if the associated context has unlimited precision and the conversion
144    /// cannot be performed losslessly.
145    #[inline]
146    pub fn to_decimal(&self) -> Rounded<FBig<HalfAway, 10>> {
147        self.clone().with_rounding().with_base::<10>()
148    }
149
150    /// Convert the float number to base 2 (with binary exponents) rounding towards zero.
151    ///
152    /// It's equivalent to `self.with_rounding::<Zero>().with_base::<2>()`.
153    ///
154    /// See [with_base()][Self::with_base] for the precision and rounding behavior.
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// # use core::str::FromStr;
160    /// # use dashu_base::ParseError;
161    /// # use dashu_float::{FBig, DBig};
162    /// use dashu_base::Approximation::*;
163    /// use dashu_float::round::{mode::HalfAway, Rounding::*};
164    ///
165    /// type Real = FBig;
166    ///
167    /// assert_eq!(
168    ///     DBig::from_str("1234")?.to_binary(),
169    ///     Exact(Real::from_str("0x4d2")?)
170    /// );
171    /// assert_eq!(
172    ///     DBig::from_str("12.34")?.to_binary(),
173    ///     Inexact(Real::from_str("0xc.57")?, NoOp)
174    /// );
175    /// assert_eq!(
176    ///     DBig::from_str("1.234e-1")?.to_binary(),
177    ///     Inexact(Real::from_str("0x1.f97p-4")?, NoOp)
178    /// );
179    /// # Ok::<(), ParseError>(())
180    /// ```
181    ///
182    /// # Panics
183    ///
184    /// Panics if the associated context has unlimited precision and the conversion
185    /// cannot be performed losslessly.
186    #[inline]
187    pub fn to_binary(&self) -> Rounded<FBig<Zero, 2>> {
188        self.clone().with_rounding().with_base::<2>()
189    }
190
191    /// Explicitly change the precision of the float number.
192    ///
193    /// If the given precision is less than the current value in the context,
194    /// it will be rounded with the rounding mode specified by the generic parameter.
195    ///
196    /// # Examples
197    ///
198    /// ```rust
199    /// # use core::str::FromStr;
200    /// # use dashu_base::ParseError;
201    /// # use dashu_float::{FBig, DBig};
202    /// use dashu_base::Approximation::*;
203    /// use dashu_float::round::{mode::HalfAway, Rounding::*};
204    ///
205    /// let a = DBig::from_str("2.345")?;
206    /// assert_eq!(a.precision(), 4);
207    /// assert_eq!(
208    ///     a.clone().with_precision(3),
209    ///     Inexact(DBig::from_str("2.35")?, AddOne)
210    /// );
211    /// assert_eq!(
212    ///     a.clone().with_precision(5),
213    ///     Exact(DBig::from_str("2.345")?)
214    /// );
215    /// # Ok::<(), ParseError>(())
216    /// ```
217    #[inline]
218    pub fn with_precision(self, precision: usize) -> Rounded<Self> {
219        let new_context = Context::new(precision);
220
221        // shrink if necessary
222        let repr = if self.context.precision > precision {
223            // it also handles unlimited precision
224            new_context.repr_round(self.repr)
225        } else {
226            Exact(self.repr)
227        };
228
229        repr.map(|v| Self::new(v, new_context))
230    }
231
232    /// Explicitly change the rounding mode of the number.
233    ///
234    /// This operation doesn't modify the underlying representation, it only changes
235    /// the rounding mode in the context.
236    ///
237    /// # Examples
238    ///
239    /// ```rust
240    /// # use core::str::FromStr;
241    /// # use dashu_base::ParseError;
242    /// # use dashu_float::{FBig, DBig};
243    /// use dashu_base::Approximation::*;
244    /// use dashu_float::round::{mode::{HalfAway, Zero}, Rounding::*};
245    ///
246    /// type DBigHalfAway = DBig;
247    /// type DBigZero = FBig::<Zero, 10>;
248    ///
249    /// let a = DBigHalfAway::from_str("2.345")?;
250    /// let b = DBigZero::from_str("2.345")?;
251    /// assert_eq!(a.with_rounding::<Zero>(), b);
252    /// # Ok::<(), ParseError>(())
253    /// ```
254    #[inline]
255    pub fn with_rounding<NewR: Round>(self) -> FBig<NewR, B> {
256        FBig {
257            repr: self.repr,
258            context: Context::new(self.context.precision),
259        }
260    }
261
262    /// Explicitly change the base of the float number.
263    ///
264    /// This function internally calls [with_base_and_precision][Self::with_base_and_precision].
265    /// The precision of the result number will be calculated in such a way that the new
266    /// limit of the significand is less than or equal to before. That is, the new precision
267    /// will be the max integer such that
268    ///
269    /// `NewB ^ new_precision <= B ^ old_precision`
270    ///
271    /// If any rounding happens during the conversion, it follows the rounding mode specified
272    /// by the generic parameter.
273    ///
274    /// # Examples
275    ///
276    /// ```rust
277    /// # use core::str::FromStr;
278    /// # use dashu_base::ParseError;
279    /// # use dashu_float::{FBig, DBig};
280    /// use dashu_base::Approximation::*;
281    /// use dashu_float::round::{mode::Zero, Rounding::*};
282    ///
283    /// type FBin = FBig;
284    /// type FDec = FBig<Zero, 10>;
285    /// type FHex = FBig<Zero, 16>;
286    ///
287    /// let a = FBin::from_str("0x1.234")?; // 0x1234 * 2^-12
288    /// assert_eq!(
289    ///     a.clone().with_base::<10>(),
290    ///     // 1.1376953125 rounded towards zero
291    ///     Inexact(FDec::from_str("1.137")?, NoOp)
292    /// );
293    /// assert_eq!(
294    ///     a.clone().with_base::<16>(),
295    ///     // conversion is exact when the new base is a power of the old base
296    ///     Exact(FHex::from_str("1.234")?)
297    /// );
298    /// # Ok::<(), ParseError>(())
299    /// ```
300    ///
301    /// # Panics
302    ///
303    /// Panics if the associated context has unlimited precision and the conversion
304    /// cannot be performed losslessly.
305    #[inline]
306    #[allow(non_upper_case_globals)]
307    pub fn with_base<const NewB: Word>(self) -> Rounded<FBig<R, NewB>> {
308        // if self.context.precision is zero, then precision is also zero
309        let precision =
310            Repr::<B>::BASE.pow(self.context.precision).log2_bounds().0 / NewB.log2_bounds().1;
311        self.with_base_and_precision(precision as usize)
312    }
313
314    /// Explicitly change the base of the float number with given precision (under the new base).
315    ///
316    /// Infinities are mapped to infinities inexactly, the error will be [NoOp][Rounding::NoOp].
317    ///
318    /// Conversion for float numbers with unlimited precision is only allowed in following cases:
319    /// - The number is infinite
320    /// - The new base NewB is a power of B
321    /// - B is a power of the new base NewB
322    ///
323    /// # Examples
324    ///
325    /// ```rust
326    /// # use core::str::FromStr;
327    /// # use dashu_base::ParseError;
328    /// # use dashu_float::{FBig, DBig};
329    /// use dashu_base::Approximation::*;
330    /// use dashu_float::round::{mode::Zero, Rounding::*};
331    ///
332    /// type FBin = FBig;
333    /// type FDec = FBig<Zero, 10>;
334    /// type FHex = FBig<Zero, 16>;
335    ///
336    /// let a = FBin::from_str("0x1.234")?; // 0x1234 * 2^-12
337    /// assert_eq!(
338    ///     a.clone().with_base_and_precision::<10>(8),
339    ///     // 1.1376953125 rounded towards zero
340    ///     Inexact(FDec::from_str("1.1376953")?, NoOp)
341    /// );
342    /// assert_eq!(
343    ///     a.clone().with_base_and_precision::<16>(8),
344    ///     // conversion can be exact when the new base is a power of the old base
345    ///     Exact(FHex::from_str("1.234")?)
346    /// );
347    /// assert_eq!(
348    ///     a.clone().with_base_and_precision::<16>(2),
349    ///     // but the conversion is still inexact if the target precision is smaller
350    ///     Inexact(FHex::from_str("1.2")?, NoOp)
351    /// );
352    /// # Ok::<(), ParseError>(())
353    /// ```
354    ///
355    /// # Panics
356    ///
357    /// Panics if the associated context has unlimited precision and the conversion
358    /// cannot be performed losslessly.
359    #[allow(non_upper_case_globals)]
360    #[inline]
361    pub fn with_base_and_precision<const NewB: Word>(
362        self,
363        precision: usize,
364    ) -> Rounded<FBig<R, NewB>> {
365        let context = Context::<R>::new(precision);
366        context
367            .convert_base(self.repr, None)
368            .map(|repr| FBig::new(repr, context))
369    }
370
371    /// Convert the float number to integer with the given rounding mode.
372    ///
373    /// # Warning
374    ///
375    /// If the float number has a very large exponent, it will be evaluated and result
376    /// in allocating an huge integer and it might eat up all your memory.
377    ///
378    /// To get a rough idea of how big the number is, it's recommended to use [EstimatedLog2].
379    ///
380    /// # Examples
381    ///
382    /// ```
383    /// # use core::str::FromStr;
384    /// # use dashu_base::ParseError;
385    /// # use dashu_float::{FBig, DBig};
386    /// use dashu_base::Approximation::*;
387    /// use dashu_float::round::Rounding::*;
388    ///
389    /// assert_eq!(
390    ///     DBig::from_str("1234")?.to_int(),
391    ///     Exact(1234.into())
392    /// );
393    /// assert_eq!(
394    ///     DBig::from_str("1.234e6")?.to_int(),
395    ///     Exact(1234000.into())
396    /// );
397    /// assert_eq!(
398    ///     DBig::from_str("1.234")?.to_int(),
399    ///     Inexact(1.into(), NoOp)
400    /// );
401    /// # Ok::<(), ParseError>(())
402    /// ```
403    ///
404    /// # Panics
405    ///
406    /// Panics if the number is infinte
407    pub fn to_int(&self) -> Rounded<IBig> {
408        assert_finite(&self.repr);
409
410        // shortcut when the number is already an integer
411        if self.repr.exponent >= 0 {
412            return Exact(shl_digits::<B>(&self.repr.significand, self.repr.exponent as usize));
413        }
414
415        let (hi, lo, precision) = self.split_at_point_internal();
416        let adjust = R::round_fract::<B>(&hi, lo, precision);
417        Inexact(hi + adjust, adjust)
418    }
419
420    /// Convert the float number to [f32] with the rounding mode associated with the type.
421    ///
422    /// Note that the conversion is inexact even if the number is infinite.
423    ///
424    /// # Examples
425    ///
426    /// ```
427    /// # use core::str::FromStr;
428    /// # use dashu_base::ParseError;
429    /// # use dashu_float::DBig;
430    /// assert_eq!(DBig::from_str("1.234")?.to_f32().value(), 1.234);
431    /// assert_eq!(DBig::INFINITY.to_f32().value(), f32::INFINITY);
432    /// # Ok::<(), ParseError>(())
433    /// ```
434    #[inline]
435    pub fn to_f32(&self) -> Rounded<f32> {
436        if self.repr.is_infinite() {
437            return Inexact(self.sign() * f32::INFINITY, Rounding::NoOp);
438        }
439
440        let context = Context::<R>::new(24);
441        context
442            .convert_base::<B, 2>(self.repr.clone(), None)
443            .and_then(|v| context.repr_round_ref(&v))
444            .and_then(|v| v.into_f32_internal())
445    }
446
447    /// Convert the float number to [f64] with the rounding mode associated with the type.
448    ///
449    /// Note that the conversion is inexact even if the number is infinite.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// # use core::str::FromStr;
455    /// # use dashu_base::ParseError;
456    /// # use dashu_float::DBig;
457    /// assert_eq!(DBig::from_str("1.234")?.to_f64().value(), 1.234);
458    /// assert_eq!(DBig::INFINITY.to_f64().value(), f64::INFINITY);
459    /// # Ok::<(), ParseError>(())
460    /// ```
461    #[inline]
462    pub fn to_f64(&self) -> Rounded<f64> {
463        if self.repr.is_infinite() {
464            return Inexact(self.sign() * f64::INFINITY, Rounding::NoOp);
465        }
466
467        let context = Context::<R>::new(53);
468        context
469            .convert_base::<B, 2>(self.repr.clone(), None)
470            .and_then(|v| context.repr_round_ref(&v))
471            .and_then(|v| v.into_f64_internal())
472    }
473}
474
475/// `isize` exponent arithmetic overflowed during base conversion: the value's magnitude
476/// falls outside the representable exponent range, so the result is ±infinity (`large`) or
477/// ±0 (`!large`). Mirrors the convention `convert_base` already uses in its division path,
478/// keeping the conversion overflow-safe (no panic) at the value level.
479#[allow(non_upper_case_globals)]
480fn converted_overflow_repr<const NewB: Word>(large: bool, sign: Sign) -> Rounded<Repr<NewB>> {
481    Inexact(
482        if large {
483            Repr::<NewB>::infinity_with_sign(sign)
484        } else {
485            Repr::<NewB>::zero_with_sign(sign)
486        },
487        Rounding::NoOp,
488    )
489}
490
491impl<R: Round> Context<R> {
492    // Convert the [Repr] from base B to base NewB, with the precision under the target base from this context.
493    #[allow(non_upper_case_globals)]
494    fn convert_base<const B: Word, const NewB: Word>(
495        &self,
496        repr: Repr<B>,
497        mut cache: Option<&mut ConstCache>,
498    ) -> Rounded<Repr<NewB>> {
499        // shortcut if NewB is the same as B
500        if NewB == B {
501            return Exact(Repr {
502                significand: repr.significand,
503                exponent: repr.exponent,
504            });
505        }
506
507        // shortcut for infinities, no rounding happens but the result is inexact
508        if repr.is_infinite() {
509            return Inexact(
510                Repr {
511                    significand: repr.significand,
512                    exponent: repr.exponent,
513                },
514                Rounding::NoOp,
515            );
516        }
517
518        if NewB > B {
519            // shortcut if NewB is a power of B
520            let n = ilog_exact(NewB, B);
521            if n > 1 {
522                let (exp, rem) = repr.exponent.div_rem_euclid(n as isize);
523                let signif = repr.significand * B.pow(rem as u32);
524                let repr = Repr::new(signif, exp);
525                return self.repr_round(repr);
526            }
527        } else {
528            // shortcut if B is a power of NewB
529            let n = ilog_exact(B, NewB);
530            if n > 1 {
531                let exp = match repr.exponent.checked_mul(n as isize) {
532                    Some(e) => e,
533                    None => return converted_overflow_repr::<NewB>(repr.exponent > 0, repr.sign()),
534                };
535                return Exact(Repr::new(repr.significand, exp));
536            }
537        }
538
539        // Shortcut: when B and NewB share common factors, factor out the common part.
540        // B = NewB^a * r where gcd(r, NewB) = 1, so B^exp = NewB^(a*exp) * r^exp.
541        // For positive exponents the result is always exact (integer multiplication).
542        // For negative exponents, exact only when r^|exp| divides the significand.
543        let (a, r) = factor_base(B, NewB);
544        if a > 0 && r > 1 {
545            if repr.exponent >= 0 {
546                let sign = repr.sign();
547                let r_exp = UBig::from_word(r).pow(repr.exponent as usize);
548                let significand = repr.significand * r_exp;
549                let exp = match (a as isize).checked_mul(repr.exponent) {
550                    Some(e) => e,
551                    None => return converted_overflow_repr::<NewB>(true, sign),
552                };
553                let new_repr = Repr::<NewB>::new(significand, exp);
554                return self.repr_round(new_repr);
555            } else {
556                let r_exp: IBig = UBig::from_word(r).pow((-repr.exponent) as usize).into();
557                if repr.significand.is_multiple_of(&r_exp) {
558                    let exp = match (a as isize).checked_mul(repr.exponent) {
559                        Some(e) => e,
560                        None => return converted_overflow_repr::<NewB>(false, repr.sign()),
561                    };
562                    let new_repr = Repr::<NewB>::new(repr.significand / r_exp, exp);
563                    return self.repr_round(new_repr);
564                }
565            }
566        }
567
568        // When NewB is a multiple of B: compute significand * B^exp directly
569        // as an integer, then express in base NewB.
570        if NewB % B == 0 && repr.exponent >= 0 {
571            let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
572            let new_repr = Repr::<NewB>::new(signif, 0);
573            return self.repr_round(new_repr);
574        }
575
576        // if the base cannot be converted losslessly, the precision must be set
577        if self.precision == 0 {
578            panic_unlimited_precision();
579        }
580
581        // choose a exponent threshold such that number with exponent smaller than this value
582        // will be converted by directly evaluating the power. The threshold here is chosen such
583        // that the power under base 10 will fit in a double word.
584        const THRESHOLD_SMALL_EXP: isize = (Word::BITS as f32 * 0.60206) as isize; // word bits * 2 / log2(10)
585        if repr.exponent.abs() <= THRESHOLD_SMALL_EXP {
586            // if the exponent is small enough, directly evaluate the exponent
587            if repr.exponent >= 0 {
588                let signif = repr.significand * Repr::<B>::BASE.pow(repr.exponent as usize);
589                Exact(Repr::new(signif, 0))
590            } else {
591                let num: Repr<NewB> = Repr::new(repr.significand, 0);
592                let den: Repr<NewB> =
593                    Repr::new(Repr::<B>::BASE.pow(-repr.exponent as usize).into(), 0);
594                match self.repr_div(num, den) {
595                    Ok(v) => v.map(|r: Repr<NewB>| Repr {
596                        significand: r.significand,
597                        exponent: r.exponent,
598                    }),
599                    Err(FpError::Overflow(sign)) => {
600                        Inexact(Repr::<NewB>::infinity_with_sign(sign), Rounding::NoOp)
601                    }
602                    Err(FpError::Underflow(sign)) => {
603                        Inexact(Repr::<NewB>::zero_with_sign(sign), Rounding::NoOp)
604                    }
605                    Err(_) => unreachable!(),
606                }
607            }
608        } else {
609            // if the exponent is large, then we first estimate the result exponent as floor(exponent * log(B) / log(NewB)),
610            // then the fractional part is multiplied with the original significand
611            let work_context = Context::<R>::new(2 * self.precision); // double the precision to get the precise logarithm
612            let new_exp = repr.exponent
613                * work_context.unwrap_fp(
614                    work_context
615                        .ln(&Repr::new(Repr::<B>::BASE.into(), 0), reborrow_cache(&mut cache)),
616                );
617            let (exponent, rem) =
618                new_exp.div_rem_euclid(work_context.ln_base::<NewB>(reborrow_cache(&mut cache)));
619            let exponent_sign = exponent.sign();
620            let exponent: isize = match exponent.try_into() {
621                Ok(v) => v,
622                Err(_) => {
623                    return converted_overflow_repr::<NewB>(
624                        exponent_sign == Sign::Positive,
625                        repr.sign(),
626                    );
627                }
628            };
629            let exp_rem = rem.exp();
630            let significand = repr.significand * exp_rem.repr.significand;
631            let repr = Repr::new(significand, exponent + exp_rem.repr.exponent);
632            self.repr_round(repr)
633        }
634    }
635}
636
637impl<const B: Word> Repr<B> {
638    // this method requires that the representation is already rounded to 24 binary bits
639    fn into_f32_internal(self) -> Rounded<f32> {
640        assert!(B == 2);
641        debug_assert!(self.is_finite());
642        debug_assert!(self.significand.bit_len() <= 24);
643
644        let sign = self.sign();
645        if self.is_neg_zero() {
646            // encode() would drop the sign of -0; preserve it exactly
647            return Exact(sign * 0f32);
648        }
649        let man24: i32 = self.significand.try_into().unwrap();
650        if self.exponent >= 128 {
651            // max f32 = 2^128 * (1 - 2^-24)
652            match sign {
653                Sign::Positive => Inexact(f32::INFINITY, Rounding::AddOne),
654                Sign::Negative => Inexact(f32::NEG_INFINITY, Rounding::SubOne),
655            }
656        } else if self.exponent < -149 - 24 {
657            // min f32 = 2^-149
658            Inexact(sign * 0f32, Rounding::NoOp)
659        } else {
660            match f32::encode(man24, self.exponent as i16) {
661                Exact(v) => Exact(v),
662                // this branch only happens when the result underflows
663                Inexact(v, _) => Inexact(v, Rounding::NoOp),
664            }
665        }
666    }
667
668    /// Convert the float number representation to a [f32] with the default IEEE 754 rounding mode.
669    ///
670    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
671    /// the float number with a specific rounding mode, please use [FBig::to_f32].
672    ///
673    /// # Examples
674    ///
675    /// ```
676    /// # use dashu_base::Approximation::*;
677    /// # use dashu_float::{Repr, round::Rounding::*};
678    /// assert_eq!(Repr::<2>::one().to_f32(), Exact(1.0));
679    /// assert_eq!(Repr::<10>::infinity().to_f32(), Inexact(f32::INFINITY, NoOp));
680    /// ```
681    #[inline]
682    pub fn to_f32(&self) -> Rounded<f32> {
683        if self.is_infinite() {
684            return Inexact(self.sign() * f32::INFINITY, Rounding::NoOp);
685        }
686
687        let context = Context::<HalfEven>::new(24);
688        context
689            .convert_base::<B, 2>(self.clone(), None)
690            .and_then(|v| context.repr_round_ref(&v))
691            .and_then(|v| v.into_f32_internal())
692    }
693
694    // this method requires that the representation is already rounded to 53 binary bits
695    fn into_f64_internal(self) -> Rounded<f64> {
696        assert!(B == 2);
697        debug_assert!(self.is_finite());
698        debug_assert!(self.significand.bit_len() <= 53);
699
700        let sign = self.sign();
701        if self.is_neg_zero() {
702            // encode() would drop the sign of -0; preserve it exactly
703            return Exact(sign * 0f64);
704        }
705        let man53: i64 = self.significand.try_into().unwrap();
706        if self.exponent >= 1024 {
707            // max f64 = 2^1024 × (1 − 2^−53)
708            match sign {
709                Sign::Positive => Inexact(f64::INFINITY, Rounding::AddOne),
710                Sign::Negative => Inexact(f64::NEG_INFINITY, Rounding::SubOne),
711            }
712        } else if self.exponent < -1074 - 53 {
713            // min f64 = 2^-1074
714            Inexact(sign * 0f64, Rounding::NoOp)
715        } else {
716            match f64::encode(man53, self.exponent as i16) {
717                Exact(v) => Exact(v),
718                // this branch only happens when the result underflows
719                Inexact(v, _) => Inexact(v, Rounding::NoOp),
720            }
721        }
722    }
723
724    /// Convert the float number representation to a [f64] with the default IEEE 754 rounding mode.
725    ///
726    /// The default IEEE 754 rounding mode is [HalfEven] (rounding to nearest, ties to even). To convert
727    /// the float number with a specific rounding mode, please use [FBig::to_f64].
728    ///
729    /// # Examples
730    ///
731    /// ```
732    /// # use dashu_base::Approximation::*;
733    /// # use dashu_float::{Repr, round::Rounding::*};
734    /// assert_eq!(Repr::<2>::one().to_f64(), Exact(1.0));
735    /// assert_eq!(Repr::<10>::infinity().to_f64(), Inexact(f64::INFINITY, NoOp));
736    /// ```
737    #[inline]
738    pub fn to_f64(&self) -> Rounded<f64> {
739        if self.is_infinite() {
740            return Inexact(self.sign() * f64::INFINITY, Rounding::NoOp);
741        }
742
743        let context = Context::<HalfEven>::new(53);
744        context
745            .convert_base::<B, 2>(self.clone(), None)
746            .and_then(|v| context.repr_round_ref(&v))
747            .and_then(|v| v.into_f64_internal())
748    }
749
750    /// Convert the float number representation to a [IBig].
751    ///
752    /// The fractional part is always rounded to zero. To convert with other rounding modes,
753    /// please use [FBig::to_int()].
754    ///
755    /// # Warning
756    ///
757    /// If the float number has a very large exponent, it will be evaluated and result
758    /// in allocating an huge integer and it might eat up all your memory.
759    ///
760    /// To get a rough idea of how big the number is, it's recommended to use [EstimatedLog2].
761    ///
762    /// # Examples
763    ///
764    /// ```
765    /// # use dashu_base::Approximation::*;
766    /// # use dashu_int::IBig;
767    /// # use dashu_float::{Repr, round::Rounding::*};
768    /// assert_eq!(Repr::<2>::neg_one().to_int(), Exact(IBig::NEG_ONE));
769    /// ```
770    ///
771    /// # Panics
772    ///
773    /// Panics if the number is infinte.
774    pub fn to_int(&self) -> Rounded<IBig> {
775        assert_finite(self);
776
777        if self.exponent >= 0 {
778            // the number is already an integer
779            Exact(shl_digits::<B>(&self.significand, self.exponent as usize))
780        } else if self.smaller_than_one() {
781            // the number is definitely smaller than
782            Inexact(IBig::ZERO, Rounding::NoOp)
783        } else {
784            let int = shr_digits::<B>(&self.significand, (-self.exponent) as usize);
785            Inexact(int, Rounding::NoOp)
786        }
787    }
788}
789
790impl<const B: Word> From<UBig> for Repr<B> {
791    #[inline]
792    fn from(n: UBig) -> Self {
793        Self::new(n.into(), 0)
794    }
795}
796impl<R: Round, const B: Word> From<UBig> for FBig<R, B> {
797    #[inline]
798    fn from(n: UBig) -> Self {
799        Self::from_parts(n.into(), 0)
800    }
801}
802
803impl<const B: Word> From<IBig> for Repr<B> {
804    #[inline]
805    fn from(n: IBig) -> Self {
806        Self::new(n, 0)
807    }
808}
809impl<R: Round, const B: Word> From<IBig> for FBig<R, B> {
810    #[inline]
811    fn from(n: IBig) -> Self {
812        Self::from_parts(n, 0)
813    }
814}
815
816impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for IBig {
817    type Error = ConversionError;
818
819    #[inline]
820    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
821        if value.repr.is_infinite() {
822            Err(ConversionError::OutOfBounds)
823        } else if value.repr.significand.is_zero() {
824            // A zero significand is integer zero regardless of exponent. This also
825            // accepts IEEE-754 signed zero, whose sign is carried by a -1 exponent
826            // sentinel (not the significand); it is treated as plain 0. The zero
827            // must be handled here rather than in the `else` branch below, which
828            // shifts by `exponent as usize` and would underflow on the -1 sentinel.
829            Ok(value.repr.significand)
830        } else if value.repr.exponent < 0 {
831            Err(ConversionError::LossOfPrecision)
832        } else {
833            let mut int = value.repr.significand;
834            shl_digits_in_place::<B>(&mut int, value.repr.exponent as usize);
835            Ok(int)
836        }
837    }
838}
839
840impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for UBig {
841    type Error = ConversionError;
842
843    #[inline]
844    fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
845        let int: IBig = value.try_into()?;
846        int.try_into()
847    }
848}
849
850macro_rules! fbig_unsigned_conversions {
851    ($($t:ty)*) => {$(
852        impl<const B: Word> From<$t> for Repr<B> {
853            #[inline]
854            fn from(value: $t) -> Repr<B> {
855                UBig::from(value).into()
856            }
857        }
858        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
859            #[inline]
860            fn from(value: $t) -> FBig<R, B> {
861                UBig::from(value).into()
862            }
863        }
864
865        impl<const B: Word> TryFrom<Repr<B>> for $t {
866            type Error = ConversionError;
867
868            fn try_from(value: Repr<B>) -> Result<Self, Self::Error> {
869                if value.sign() == Sign::Negative || value.is_infinite() {
870                    Err(ConversionError::OutOfBounds)
871                } else {
872                    let (log2_lb, _) = value.log2_bounds();
873                    if log2_lb >= <$t>::BITS as f32 {
874                        Err(ConversionError::OutOfBounds)
875                    } else if value.exponent < 0 {
876                        Err(ConversionError::LossOfPrecision)
877                    } else {
878                        shl_digits::<B>(&value.significand, value.exponent as usize).try_into()
879                    }
880                }
881            }
882        }
883        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
884            type Error = ConversionError;
885
886            #[inline]
887            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
888                value.repr.try_into()
889            }
890        }
891    )*};
892}
893fbig_unsigned_conversions!(u8 u16 u32 u64 u128 usize);
894
895macro_rules! fbig_signed_conversions {
896    ($($t:ty)*) => {$(
897        impl<R: Round, const B: Word> From<$t> for FBig<R, B> {
898            #[inline]
899            fn from(value: $t) -> FBig<R, B> {
900                IBig::from(value).into()
901            }
902        }
903
904        impl<R: Round, const B: Word> TryFrom<FBig<R, B>> for $t {
905            type Error = ConversionError;
906
907            fn try_from(value: FBig<R, B>) -> Result<Self, Self::Error> {
908                if value.repr.is_infinite() {
909                    Err(ConversionError::OutOfBounds)
910                } else {
911                    let (log2_lb, _) = value.repr.log2_bounds();
912                    if log2_lb >= <$t>::BITS as f32 {
913                        Err(ConversionError::OutOfBounds)
914                    } else if value.repr.exponent < 0 {
915                        Err(ConversionError::LossOfPrecision)
916                    } else {
917                        shl_digits::<B>(&value.repr.significand, value.repr.exponent as usize).try_into()
918                    }
919                }
920            }
921        }
922    )*};
923}
924fbig_signed_conversions!(i8 i16 i32 i64 i128 isize);
925
926macro_rules! impl_from_fbig_for_float {
927    ($t:ty, $method:ident) => {
928        impl TryFrom<Repr<2>> for $t {
929            type Error = ConversionError;
930
931            #[inline]
932            fn try_from(value: Repr<2>) -> Result<Self, Self::Error> {
933                if value.is_infinite() {
934                    Err(ConversionError::LossOfPrecision)
935                } else {
936                    match value.$method() {
937                        Exact(v) => Ok(v),
938                        Inexact(v, _) => {
939                            if v.is_infinite() {
940                                Err(ConversionError::OutOfBounds)
941                            } else {
942                                Err(ConversionError::LossOfPrecision)
943                            }
944                        }
945                    }
946                }
947            }
948        }
949
950        impl<R: Round> TryFrom<FBig<R, 2>> for $t {
951            type Error = ConversionError;
952
953            #[inline]
954            fn try_from(value: FBig<R, 2>) -> Result<Self, Self::Error> {
955                // this method is the same as the one for Repr, but it has to be re-implemented
956                // because the rounding behavior of to_32/to_64 is different.
957                if value.repr.is_infinite() {
958                    Err(ConversionError::LossOfPrecision)
959                } else {
960                    match value.$method() {
961                        Exact(v) => Ok(v),
962                        Inexact(v, _) => {
963                            if v.is_infinite() {
964                                Err(ConversionError::OutOfBounds)
965                            } else {
966                                Err(ConversionError::LossOfPrecision)
967                            }
968                        }
969                    }
970                }
971            }
972        }
973    };
974}
975impl_from_fbig_for_float!(f32, to_f32);
976impl_from_fbig_for_float!(f64, to_f64);
977
978#[cfg(test)]
979mod tests {
980    use super::*;
981    use crate::repr::Repr;
982
983    #[test]
984    fn ibig_try_from_accepts_signed_zero() {
985        // IEEE-754 signed zero (sign encoded in a -1 exponent sentinel) is plain 0.
986        let neg_zero = FBig::<HalfAway, 10>::new(Repr::neg_zero(), Context::new(8));
987        assert_eq!(IBig::try_from(neg_zero), Ok(IBig::from(0)));
988
989        // positive zero already worked, and still does
990        let pos_zero = FBig::<HalfAway, 10>::new(Repr::zero(), Context::new(8));
991        assert_eq!(IBig::try_from(pos_zero), Ok(IBig::from(0)));
992
993        // UBig delegates to the IBig impl, so it accepts signed zero too
994        let neg_zero = FBig::<HalfAway, 2>::new(Repr::neg_zero(), Context::new(8));
995        assert_eq!(UBig::try_from(neg_zero), Ok(UBig::from(0u8)));
996
997        // a genuine fractional value must still be rejected
998        let frac = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(1), -1), Context::new(8));
999        assert_eq!(IBig::try_from(frac), Err(ConversionError::LossOfPrecision));
1000
1001        // a normal integer round-trips exactly
1002        let int_val = FBig::<HalfAway, 10>::new(Repr::new(IBig::from(42), 0), Context::new(8));
1003        assert_eq!(IBig::try_from(int_val), Ok(IBig::from(42)));
1004    }
1005}