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,596 questions

55,330 answers

573 users

How to convert a decimal to a long in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

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

    This program demonstrates:
      • Conversion using lround(), which rounds to the nearest integer.
      • Conversion using a direct cast (long), which truncates toward zero.
      • A helper function that prints both results for comparison.

    Notes:
      • C does not have a built-in decimal type.
      • double or long double are used for decimal values.
      • lround() follows IEEE rounding rules.
      • (long)value truncates the fractional part.
    ============================================================
*/

/* Converts a floating decimal value to long using rounding */
long convert_decimal_to_long(double value) {
    return lround(value);
}

/* Converts a floating decimal value to long using truncation */
long cast_decimal_to_long(double value) {
    return (long)value;
}

/* Prints both conversion styles for comparison */
void show_conversions(double value) {
    printf("Input decimal: %.4f\n", value);

    long rounded   = convert_decimal_to_long(value);
    long truncated = cast_decimal_to_long(value);

    printf("Rounded (lround): %ld\n", rounded);
    printf("Truncated (cast to long): %ld\n\n", truncated);
}

int main(void) {
    /* Example values to demonstrate behavior */
    show_conversions(12.7);
    show_conversions(12.3);
    show_conversions(-5.8);
    show_conversions(42.0);   /* already an integer */

    return 0;
}


/*
run:

Input decimal: 12.7000
Rounded (lround): 13
Truncated (cast to long): 12

Input decimal: 12.3000
Rounded (lround): 12
Truncated (cast to long): 12

Input decimal: -5.8000
Rounded (lround): -6
Truncated (cast to long): -5

Input decimal: 42.0000
Rounded (lround): 42
Truncated (cast to long): 42

*/

 



answered 1 day ago by avibootz
...