std::float (v0.2.2)

Parsing of floating-point values from text.

Latest

Overview

std::float parses floating-point values from C strings and TString values into f32, f80, or f64.

parse[T] returns a result struct with the parsed value and a success flag, mirroring the integer parsing helpers.

Source: thrustc/std/v0.2.2/float.thrust

Public Signatures

Exported declarations for this module snapshot.

struct ParseF32Result @public {
struct ParseF64Result @public {
struct ParseF80Result @public {
fn parse [T] (text: CString) T @public;
fn parseCString [T] (text: CString) T @public;
fn parseTString [T] (text: ptr[tstring::TString]) T @public;
fn parseF32(text: CString) ParseF32Result @public;
fn parseF32CString(text: CString) ParseF32Result @public;
fn parseF32TString(text: ptr[tstring::TString]) ParseF32Result @public;
fn parseF64(text: CString) ParseF64Result @public;
fn parseF64CString(text: CString) ParseF64Result @public;
fn parseF64TString(text: ptr[tstring::TString]) ParseF64Result @public;
fn parseF80(text: CString) ParseF80Result @public;
fn parseF80CString(text: CString) ParseF80Result @public;
fn parseF80TString(text: ptr[tstring::TString]) ParseF80Result @public;

Behavior and Use

parse[T] returns a result struct with a success flag and supports f32, f80, and f64 targets.

Parsing follows C library rules for format and range; check the success flag before using the value.

Examples

import std::float;
import std::io;

// Turn a Celsius text reading into Fahrenheit and print the whole part.
fn main() s32 @public {
    var celsius: f64 = float::parse[f64]("25.0");
    var fahrenheit: f64 = celsius * 9.0 / 5.0 + 32.0;

    io::print("fahrenheit: %d\n", (fahrenheit as s32));

    return 0;
}
import std::float;
import std::io;

// Parse a single-precision reading and show its whole part.
fn main() s32 @public {
    var value: f32 = float::parse[f32]("3.5");
    var whole: s32 = value as s32;

    io::print("whole part: %d\n", whole);

    return 0;
}
import std::float;
import std::io;

// Parse a reading that may be malformed, checking the result first.
fn main() s32 @public {
    var result := float::parseF64("2.5");

    if !(result->ok) {
        io::print("could not parse\n");
        return 0;
    }

    io::print("value: %d\n", (result->value as s32));

    return 0;
}

Notes

Back to std index