rust-lang / rust-lang/rfcs

std/core feature request: Converting floats to ints without `as`

Open
#3,304 15 comments 18 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

Currently there are only two ways to cast floats to integers

  1. as casts
  2. to_int_unchecked

Adding explicit conversion functions could make casting a bit easier.
I would propose the functions to_int_saturating and to_int_checked.
Where to_int_saturating works like as conversions, and to_int_checked is a safe version of to_int_unchecked which returns an Option and does not accept any fractional part.

Examples:

// Saturating conversion
assert_eq!(257.64f64.to_int_saturating::<u8>(), 255);
assert_eq!(232.7f64.to_int_saturating::<u8>(), 232);

// Checked conversions
assert!(257.64f64.to_int_checked::<u8>().is_none());
assert!(232.74f64.to_int_checked::<i32>().is_none());
assert!(232.73f64.to_int_checked::<i32>().is_none());
assert_eq!(232.0f64.to_int_checked::<u8>(), Some(232));

I think the to_int_checked function would be a great new feature and using a more explicit version of as casts also helps. I think creating alterntives to as many as casts as possible is desirable.

With some pointers i might also be able to help implementing this, if there is interest in implementing this feature.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing as conversions and to_int_unchecked behavior described in this issue, along with the proposed examples. Determine the API and semantics for to_int_saturating and to_int_checked, including fractional and out-of-range values, then define the RFC-level design and acceptance criteria.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.