Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to convert a decimal to a long in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>
#include <string>

/*
    ============================================================
    Convert a decimal-like value to a long in C++.

    This program demonstrates:
      • Conversion using std::lround(), which rounds to nearest.
      • Conversion using static_cast<long>(), which truncates.
      • A helper function that prints both results.

    Notes:
      • C++ does not have a built-in decimal type.
      • double or long double are used for decimal values.
      • std::lround() follows IEEE rounding rules.
      • static_cast<long>() truncates toward zero.
    ============================================================
*/

class DecimalToLongProgram {
public:

    // Converts a floating decimal value to long using rounding.
    static long ConvertDecimalToLong(double value) {
        return std::lround(value);
    }

    // Converts a floating decimal value to long using truncation.
    static long CastDecimalToLong(double value) {
        return static_cast<long>(value);
    }

    // Prints both conversion styles for comparison.
    static void ShowConversions(double value) {
        std::cout << "Input decimal: " << value << "\n";

        long rounded   = ConvertDecimalToLong(value);
        long truncated = CastDecimalToLong(value);

        std::cout << "Rounded (std::lround): " << rounded << "\n";
        std::cout << "Truncated (static_cast<long>): " << truncated << "\n\n";
    }
};

int main() {
    // Example values to demonstrate behavior
    DecimalToLongProgram::ShowConversions(12.7);
    DecimalToLongProgram::ShowConversions(12.3);
    DecimalToLongProgram::ShowConversions(-5.8);
    DecimalToLongProgram::ShowConversions(42.0);   // already an integer
}



/*
run:

Input decimal: 12.7
Rounded (std::lround): 13
Truncated (static_cast<long>): 12

Input decimal: 12.3
Rounded (std::lround): 12
Truncated (static_cast<long>): 12

Input decimal: -5.8
Rounded (std::lround): -6
Truncated (static_cast<long>): -5

Input decimal: 42
Rounded (std::lround): 42
Truncated (static_cast<long>): 42

*/

 



answered Aug 6 by avibootz
...